diff --git a/packages/shell/src/services/validate.ts b/packages/shell/src/services/validate.ts new file mode 100644 index 0000000..7ac59b4 --- /dev/null +++ b/packages/shell/src/services/validate.ts @@ -0,0 +1,27 @@ +import type { Schema } from 'ajv' +import Ajv from 'ajv' +import localize from 'ajv-i18n/localize/zh' +import schemas from '../../generated/schemas.json' + +const ajv = new Ajv({ + discriminator: true, + useDefaults: true, +}) + +ajv.addKeyword({ + keyword: 'defaultProperties', + valid: true, +}) + +ajv.addSchema(schemas as Schema[]) + +export const validate = (id: string) => async (data: unknown) => { + const validate = ajv.getSchema(id) + if (await validate!(data)) return undefined + localize(validate!.errors) + let e = '' + let i = 0 + for (const error of validate!.errors!) + e += `\t问题 ${++i}:${error.schemaPath}:${error.message}` + return e +} diff --git a/tsconfig.base.json b/tsconfig.base.json index 8ddfbc5..35c3b33 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -10,5 +10,6 @@ "skipLibCheck": true, "esModuleInterop": true, "moduleResolution": "node", + "resolveJsonModule": true, } }