All files / webapp/model jsonArrayParser.ts

100% Statements 10/10
100% Branches 7/7
100% Functions 2/2
100% Lines 10/10

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                                          8x 8x   2x     6x 2x     4x 7x             4x 2x     2x    
/**
 * Discriminated-union result of {@link parseJsonArrayOfObjects}. Carries the
 * failure kind instead of showing an error message itself, since the i18n
 * text differs per caller (PAM vs. own-products data, App vs. Main vs.
 * MyProducts controller).
 */
export type JsonArrayParseResult =
    | { kind: "parseError" }
    | { kind: "notArray" }
    | { kind: "invalidEntries" }
    | { kind: "ok"; data: Record<string, unknown>[] };
 
/**
 * Validates uploaded JSON file content against the shape expected by
 * PAM.json/OwnProducts.json: an array of plain objects.
 * @param fileContent The raw file content to parse
 * @returns The parsed data on success, or which validation step failed
 */
export function parseJsonArrayOfObjects(fileContent: string): JsonArrayParseResult {
    let parsedContent: unknown;
 
    try {
        parsedContent = JSON.parse(fileContent);
    } catch {
        return { kind: "parseError" };
    }
 
    if (!Array.isArray(parsedContent)) {
        return { kind: "notArray" };
    }
 
    const containsInvalidEntry = parsedContent.some((entry) => {
        return (
            typeof entry !== "object" ||
            entry === null ||
            Array.isArray(entry)
        );
    });
 
    if (containsInvalidEntry) {
        return { kind: "invalidEntries" };
    }
 
    return { kind: "ok", data: parsedContent as Record<string, unknown>[] };
}