diff --git a/helpers/Dojo/SharedEnonceHelper.ts b/helpers/Dojo/SharedEnonceHelper.ts new file mode 100644 index 0000000000000000000000000000000000000000..f8ae6c40f459b1cce8a5517dbc7c7762cd43411b --- /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