import Ajv, { ErrorObject, JTDSchemaType } from 'ajv/dist/jtd'; import fs from 'fs'; import JSON5 from 'json5'; import AssignmentFile from '../../types/Dojo/AssignmentFile'; class SharedAssignmentHelper { private validateDescriptionFileV1(resultsFilePathOrStr: string, isFile: boolean = true): { results: AssignmentFile | undefined, isValid: boolean, errors: Array<ErrorObject | string> | null | undefined } { const ajv = new Ajv(); const schema: JTDSchemaType<AssignmentFile> = { properties : { dojoAssignmentVersion: { type: 'uint32' }, version : { type: 'uint32' }, immutable: { elements: { properties : { path: { type: 'string' } }, optionalProperties: { description: { type: 'string' }, isDirectory: { type: 'boolean' } } } }, result: { properties : { container: { type: 'string' } }, optionalProperties: { 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: AssignmentFile | 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 SharedAssignmentHelper();