From 640d3261c369dce0c5440aa5f6f9cdbbfd3195e2 Mon Sep 17 00:00:00 2001 From: Il Harper Date: Mon, 4 Mar 2024 02:02:57 +0800 Subject: [PATCH] feat(shell): add validate svc --- packages/shell/src/services/validate.ts | 27 +++++++++++++++++++++++++ tsconfig.base.json | 1 + 2 files changed, 28 insertions(+) create mode 100644 packages/shell/src/services/validate.ts 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, } }