【发布时间】:2021-07-19 13:50:12
【问题描述】:
我正在使用 AJV 库 https://github.com/ajv-validator/ajv 来验证我的 nodejs express api 的输入。但是,我无法为返回的数组中的每个错误对象提取有问题的属性名称。
[{
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'
}]
从上面的输出中可以看出,为每个提取属性名称(start_date, top)有点不同,所以我希望有一种简单的方法可以做到这一点,而不必根据错误类型(关键字)进行解析.
期待
我希望能够创建如下映射原始数组的错误。为此,我需要上述原始输出中可用的消息和不可用的属性名称。
[
{ property: "start_date", message: "must have required property 'start_date"}
{ property: "top", message: "must be number" },
]
代码
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"
【问题讨论】:
标签: javascript node.js ajv