From f33e4e0c7b34f9060e8995550920d25cd3e73c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me> Date: Fri, 11 Aug 2023 23:15:55 +0200 Subject: [PATCH] EnonceHelper => Add enonce file validation --- helpers/Dojo/SharedEnonceHelper.ts | 71 ++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 helpers/Dojo/SharedEnonceHelper.ts diff --git a/helpers/Dojo/SharedEnonceHelper.ts b/helpers/Dojo/SharedEnonceHelper.ts new file mode 100644 index 0000000..f8ae6c4 --- /dev/null +++ b/helpers/Dojo/SharedEnonceHelper.ts @@ -0,0 +1,71 @@ +import Ajv, { ErrorObject, JTDSchemaType } from 'ajv/dist/jtd'; +import fs from 'fs'; +import JSON5 from 'json5'; +import EnonceFile from '../../types/Dojo/EnonceFile'; + + +class SharedEnonceHelper { + private validateDescriptionFileV1(resultsFilePathOrStr: string, isFile: boolean = true): { results: EnonceFile | undefined, isValid: boolean, errors: Array<ErrorObject | string> | null | undefined } { + const ajv = new Ajv(); + + const schema: JTDSchemaType<EnonceFile> = { + properties : { + dojoEnonceVersion: { type: 'uint32' }, + version : { type: 'uint32' }, + + immutable: { + elements: { + properties: { + description: { type: 'string' }, + path : { type: 'string' }, + isDirectory: { type: 'boolean' } + } + } + }, + + result: { + properties: { + container: { type: 'string' }, + volume : { type: 'string' } + } + } + }, + additionalProperties: false + }; + + const validator = ajv.compile(schema); + + try { + const results = JSON5.parse(isFile ? fs.readFileSync(resultsFilePathOrStr, 'utf8') : resultsFilePathOrStr); + const isValid = validator(results); + + return { + results: isValid ? results : results as any, + isValid: isValid, + errors : validator.errors + }; + } catch ( error ) { + return { + results: undefined, + isValid: false, + errors : [ `JSON5 invalid : ${ JSON.stringify(error) }` ] + }; + } + } + + validateDescriptionFile(resultsFilePathOrStr: string, isFile: boolean = true, version: number = 1): { results: EnonceFile | undefined, isValid: boolean, errors: Array<ErrorObject | string> | null | undefined } { + switch ( version ) { + case 1: + return this.validateDescriptionFileV1(resultsFilePathOrStr, isFile); + default: + return { + results: undefined, + isValid: false, + errors : [ `Version ${ version } not supported` ] + }; + } + } +} + + +export default new SharedEnonceHelper(); \ No newline at end of file -- GitLab