Skip to content
Snippets Groups Projects
Commit ace21995 authored by michael.minelli's avatar michael.minelli
Browse files

Json5FileValidator => Add a function to test JSON5 file or str compared to a zod schema

parent 3d82f7c2
No related branches found
No related tags found
No related merge requests found
import JSON5 from 'json5';
import fs from 'fs';
import { z, ZodError } from 'zod';
import { fromZodError } from 'zod-validation-error';
class Json5FileValidator {
validateFile<T>(schema: z.ZodType<T>, filePathOrStr: string, isFile: boolean = true, resultSanitizer: (value: T) => T = value => value): { content: T | undefined, isValid: boolean, error: string | null } {
let parsedInput: T;
try {
parsedInput = JSON5.parse(isFile ? fs.readFileSync(filePathOrStr, 'utf8') : filePathOrStr);
} catch ( error ) {
return {
content: undefined,
isValid: false,
error : `JSON5 invalid : ${ JSON.stringify(error) }`
};
}
try {
return {
content: resultSanitizer(schema.parse(parsedInput) as unknown as T),
isValid: true,
error : null
};
} catch ( error ) {
if ( error instanceof ZodError ) {
return {
content: parsedInput,
isValid: false,
error : fromZodError(error).toString()
};
}
return {
content: parsedInput,
isValid: false,
error : `Unknown error : ${ JSON.stringify(error) }`
};
}
}
}
export default new Json5FileValidator();
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment