diff --git a/helpers/Json5FileValidator.ts b/helpers/Json5FileValidator.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9be717bbf249bdb6230b187deb1e1fc948a2274 --- /dev/null +++ b/helpers/Json5FileValidator.ts @@ -0,0 +1,46 @@ +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