我正在尝试开始使用 Middy 来验证 AWS lambda 上的输入架构。
下面的 lambda 函数不断抛出此错误:
中间件必须是一个对象,其中至少包含“before”、“after”、“onError”中的一个键
有人知道可能是什么问题吗?
我在奔跑
Node v18.12.1
"@middy/core": "^4.0.2",
"@middy/http-error-handler": "^4.0.2",
"@middy/http-json-body-parser": "^4.0.2",
"@middy/validator": "^4.0.2",
这是 lambda 代码
import middy from "@middy/core";
import validator from "@middy/validator";
import httpErrorHandler from "@middy/http-error-handler";
import jsonBodyParser from "@middy/http-json-body-parser";
const baseHandler = (event) => {
const { fname, lname } = event.body;
return {
statusCode: 200,
headers: { "Content-Type": "text/plain" },
body: `Hello, ${fname}-${lname}.`,
};
};
const inputSchema = {
type: "object",
properties: {
body: {
type: "object",
properties: {
fname: { type: "string" },
lname: { type: "string" },
},
required: ["fname", "lname"],
},
},
};
const handler = middy(baseHandler)
.use(jsonBodyParser())
.use(
validator({
inputSchema,
})
)
.use(httpErrorHandler());
export { handler };
我预计当未向函数提供输入参数时验证器会抛出错误
谢谢威尔·法雷尔
将 inputSchema 更改为 eventSchema。该名称在 v3 中更改,并在 v4 中完全删除。
尝试使用
validatorMiddleware
代替 validator
,将 inputSchema
重命名为 eventSchema
,并将模式对象传递到实用函数 transpileSchema
中。希望这有帮助!
添加了响应模式的工作版本:
import middy from '@middy/core';
import validatorMiddleware from '@middy/validator';
import { transpileSchema } from '@middy/validator/transpile';
import httpErrorHandler from '@middy/http-error-handler';
import jsonBodyParser from '@middy/http-json-body-parser';
const baseHandler = (event) => {
const { fname, lname } = event.body;
return {
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
body: `Hello, ${fname}-${lname}.`,
};
};
const eventJsonSchema = {
type: 'object',
properties: {
body: {
type: 'object',
properties: {
fname: { type: 'string' },
lname: { type: 'string' },
},
required: ['fname', 'lname'],
},
},
};
const responseJsonSchema = {
type: 'object',
required: ['body', 'statusCode'],
properties: {
body: {
type: 'string',
},
statusCode: {
type: 'number',
},
headers: {
type: 'object',
},
},
};
const handler = middy(baseHandler)
.use(jsonBodyParser())
.use(
validatorMiddleware({
eventSchema: transpileSchema(eventJsonSchema),
responseSchema: transpileSchema(responseJsonSchema),
})
)
.use(httpErrorHandler());
export { handler };