All files / owid-grapher/clientUtils patchHelper.ts

66.02% Statements 68/103
71.43% Branches 10/14
33.33% Functions 1/3
66.02% Lines 68/103

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 1171x 1x 1x 40x 40x 40x 40x 40x 40x 40x 11x 40x 29x 29x 29x 29x 24x 24x 24x 24x 19x 19x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 29x 5x 5x 5x 1x 1x 1x     1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 29x 40x 1x               1x                                                                    
import jsonpointer from "json8-pointer"
import { VariableAnnotationPatch } from "./AdminSessionTypes"
import { isArray, isPlainObjectWithGuard } from "./Util"
export function setValueRecursive(
    json: any,
    pointer: string[],
    newValue: any
): any {
    // If the pointer is empty at this recursion level then just return newValue
    if (pointer.length == 0) {
        return newValue
    } else {
        // We check if the currently relevant part of the pointer is a number or a string
        const currentPart = pointer[0]
        const currentPartAsNumber = Number.parseInt(currentPart)
        if (Number.isNaN(currentPartAsNumber)) {
            // If we have a string then recurse into the object
            let newObject: any = {}
            if (json !== undefined) newObject = { ...json }
            const currentValue = newObject.hasOwnProperty(currentPart)
                ? newObject[currentPart]
                : undefined
            const updatedValue = setValueRecursive(
                currentValue,
                pointer.slice(1),
                newValue
            )
            // if we got a null back as the result of the update operation
            // then delete the key, otherwise set the property to the updated value
            if (updatedValue === null) delete newObject[currentPart]
            else newObject[currentPart] = updatedValue
            return newObject
        } else {
            // we have a number as a key. Either there is already an array at this place
            // and we should update or append it or we need to create a new array (else branch below)
            if (isArray(json)) {
                const newArray = [...json]
                const oldValue =
                    currentPartAsNumber < newArray.length
                        ? newArray[currentPartAsNumber]
                        : undefined
                const updatedValue = setValueRecursive(
                    oldValue,
                    pointer.slice(1),
                    newValue
                )
                if (updatedValue === null) {
                    // if the updated value is null then remove this item
                    //   if this is a valid index, splice it out
                    if (currentPartAsNumber < newArray.length) {
                        newArray.splice(currentPartAsNumber, 1)
                    }
                    // otherwise ignore it since it is not in the array yet anyhow
                } else {
                    if (currentPartAsNumber < newArray.length) {
                        newArray[currentPartAsNumber] = updatedValue
                    } else newArray.push(updatedValue)
                }
                return newArray
            } else {
                // if we have a number as key but no array at the current position, then we need to create a new array.
                // If the value is nested inside we still need to create the correct substructure inside the new array, so
                // recurse but with null as the current json value to create the nested substructure
                const updatedValue = setValueRecursive(
                    null,
                    pointer.slice(1),
                    newValue
                )
                if (updatedValue == null) return null
                else return [updatedValue]
            }
        }
    }
}
 
export function compileGetValueFunction(jsonPointer: string): (x: any) => any {
    // TODO: the json8-pointer libarary compile function does not return undefined
    // if the item can't be found like find but instead throws. Probably it makes sense
    // to try to create a more efficient version here that does not throw exceptions since
    // this will be used very often in an inner loop
    return (input): any => jsonpointer.find(input, jsonPointer)
}
 
export function applyPatch(
    patchSet: VariableAnnotationPatch,
    config: unknown
): any {
    const pointer = jsonpointer.parse(patchSet.jsonPointer) as string[]

    if (pointer.length == 0) throw Error("Empty JSON path is not supported")
    if (
        config !== undefined &&
        config !== null &&
        !(isArray(config) || isPlainObjectWithGuard(config))
    ) {
        throw Error(
            "When given an non-empty pointer, config must be either an object or array but it is " +
                typeof config
        )
    }

    const currentValue = jsonpointer.find(config, patchSet.jsonPointer)

    if (
        currentValue !== patchSet.oldValue &&
        !(currentValue === undefined && patchSet.oldValue === null)
    ) {
        console.warn(
            `When trying to set value for ${patchSet.variableId} at ${patchSet.jsonPointer}, the existing value was ${currentValue} instead of ${patchSet.oldValue}`
        )
        throw Error("Old value was not as expected")
    }
 
    const newConfig = setValueRecursive(config, pointer, patchSet.newValue)
    return newConfig
}