From f552a2cf4640f5bf669d7cd12495c1abc3f2acfa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me>
Date: Thu, 3 Aug 2023 23:07:00 +0200
Subject: [PATCH] Add ExerciceHelper with results json file validation

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

diff --git a/helpers/ExerciceHelper.ts b/helpers/ExerciceHelper.ts
new file mode 100644
index 0000000..fccaefe
--- /dev/null
+++ b/helpers/ExerciceHelper.ts
@@ -0,0 +1,49 @@
+import Ajv, { ErrorObject, JTDSchemaType } from 'ajv/dist/jtd';
+import fs                                  from 'fs-extra';
+import ExerciceResultsFile                 from '../types/Dojo/ExerciceResultsFile';
+import hjson                               from 'hjson';
+
+
+class ExerciceHelper {
+    validateResultFile(resultsFilePath: string): {
+        results: ExerciceResultsFile, isValid: boolean, errors: ErrorObject<string, Record<string, any>, unknown>[] | null | undefined
+    } {
+        const ajv = new Ajv();
+
+        const schema: JTDSchemaType<ExerciceResultsFile> = {
+            properties          : {
+                success: { type: 'boolean' }
+            },
+            optionalProperties  : {
+                successfulTests: { type: 'uint32' },
+                failedTests    : { type: 'uint32' },
+
+                successfulTestsList: {
+                    elements: {
+                        type: 'string'
+                    }
+                },
+                failedTestsList    : {
+                    elements: {
+                        type: 'string'
+                    }
+                }
+            },
+            additionalProperties: false
+        };
+
+        const validator = ajv.compile(schema);
+
+        const results = hjson.parse(fs.readFileSync(resultsFilePath, 'utf8'));
+        const isValid = validator(results);
+
+        return {
+            results: isValid ? results as ExerciceResultsFile : results as any,
+            isValid: isValid,
+            errors : validator.errors
+        };
+    }
+}
+
+
+export default new ExerciceHelper();
\ No newline at end of file
-- 
GitLab