Estoy usando la biblioteca AJV https://github.com/ajv-validator/ajv para validar la entrada de mi nodejs express api. Sin embargo, tengo problemas para extraer el nombre de la propiedad en cuestión para cada objeto de error en la matriz devuelta.
[{ instancePath: '', schemaPath: '#/required', keyword: 'required', params: { missingProperty: 'start_date' }, message: "must have required property 'start_date'" } { instancePath: '/top', schemaPath: '#/properties/top/type', keyword: 'type', params: { type: 'number' }, message: 'must be number' }] Como puede ver en el resultado anterior, extraer el nombre de la propiedad ( start_date, top ) para cada uno es un poco diferente, por lo que espero que haya una manera fácil de hacerlo sin tener que analizar según el tipo de error (palabra clave).
Expectativa
espero poder crear un error como el siguiente mapeando la matriz original. Para hacer eso, necesito el mensaje que está disponible en la salida original anterior y el nombre de la propiedad que no está disponible.
[ { property: "start_date", message: "must have required property 'start_date"} { property: "top", message: "must be number" }, ]Código
export interface ILeaderboardQuery { rank: string; entity_types: string[]; country?: string | undefined; region?: string | undefined; start_date: string; end_date: string; top?: number | undefined; } export const LeaderboardQuerySchema: JSONSchemaType<ILeaderboardQuery> = { type: "object", properties: { rank: { type: "string" }, entity_types: { type: "array", items: { type: "string", }, }, country: { type: "string", nullable: true }, region: { type: "string", nullable: true }, start_date: { type: "string" }, end_date: { type: "string" }, top: { type: "number", nullable: true }, }, required: ["rank", "start_date", "end_date"], additionalProperties: false, }; const ajv = new Ajv({ allErrors: true }); export const GetLeaderboardValidator = (req: Request, res: Response, next: NextFunction) => { const validate = ajv.compile<ILeaderboardQuery>(LeaderboardQuerySchema); for (const err of validate.errors as DefinedError[]) { console.log(err); } }; ajv : ^8.6.2"
Puede usar el paquete ajv-errors si no le importa agregar jerga de esquema adicional que no sea JSON en su esquema.
Puede agregar un mensaje de errorMessage adicional a cualquier esquema. Se puede configurar como una cadena o como un objeto. Si se establece en un objeto, sus claves se establecen en reglas y los valores se establecen en mensajes de error.
Esperemos que esto tenga sentido:
const Ajv = require('ajv'); const ajvErrors = require('ajv-errors'); const ajv = new Ajv({allErrors: true}); ajvErrors(ajv); const validate = ajv.compile({ type: "object", required: ["foo"], additionalProperties: false, properties: { foo: { type: "number", errorMessage: "CUSTOM ERROR: foo must be a number" } }, errorMessage: { type: "CUSTOM ERROR: not an object", required: "CUSTOM ERROR: missing required property foo", additionalProperties: "CUSTOM ERROR: cannot have other properties" } }); validate("foo"); validate.errors; /* [ { instancePath: '', schemaPath: '#/errorMessage', keyword: 'errorMessage', params: { errors: [Array] }, message: 'CUSTOM ERROR: not an object' } ] */ validate({}); validate.errors; /* [ { instancePath: '', schemaPath: '#/errorMessage', keyword: 'errorMessage', params: { errors: [Array] }, message: 'CUSTOM ERROR: missing required property foo' } ] */ validate({foo: 1, bar: 2}); validate.errors; /* [ { instancePath: '', schemaPath: '#/errorMessage', keyword: 'errorMessage', params: { errors: [Array] }, message: 'CUSTOM ERROR: cannot have other properties' } ] */ validate({foo: "wat"}); validate.errors; /* [ { instancePath: '/foo', schemaPath: '#/properties/foo/errorMessage', keyword: 'errorMessage', params: { errors: [Array] }, message: 'CUSTOM ERROR: foo must be a number' } ] */