From ace219958cbfc122c9fb4812ba136cf84e0a7a10 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me>
Date: Thu, 18 Jan 2024 00:20:39 +0100
Subject: [PATCH] Json5FileValidator => Add a function to test JSON5 file or
 str compared to a zod schema

---
 helpers/Json5FileValidator.ts | 46 +++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
 create mode 100644 helpers/Json5FileValidator.ts

diff --git a/helpers/Json5FileValidator.ts b/helpers/Json5FileValidator.ts
new file mode 100644
index 0000000..c9be717
--- /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
-- 
GitLab