如何使用Middy在Serverless AWS Lambda中验证年份字段为4位?
解决Middy中JSON Schema验证年份为4位数字的问题
你遇到的问题是因为length是JSON Schema中仅针对字符串类型的验证关键字,对数字类型不生效。要实现年份必须是4位数字的约束,需要用数字类型的专属验证规则:
- 将
year的类型从number更改为integer(年份是整数,更精准) - 使用
minimum和maximum限定数值范围,确保年份在1000到9999之间(包含边界)
修改后的inputSchema代码如下:
const inputSchema = { type: "object", properties: { body: { type: "object", properties: { year: { type: "integer", minimum: 1000, maximum: 9999 }, questionId: { type: "string" }, propSeq: { type: "number" }, questionTitle: { type: "string" }, propContent: { type: "string" }, isTrue: { type: "boolean" }, chapter: { type: "number" } }, required: ["year", "questionId", "propSeq", "questionTitle", "propContent", "isTrue", "chapter"], }, }, };
这样配置后,Middy的validator中间件会自动拦截不符合4位整数要求的年份请求,无需在baseHandler中额外编写验证逻辑。
内容的提问来源于stack exchange,提问作者hardyeats
相关产品推荐
相关产品推荐

