我使用TypeScript模板创建了一个全新的项目:
$ serverless create --template aws-nodejs-typescript --path demo我编辑了tsconfig.json并启用了strictNullChecks,因为我更喜欢打开这个特性:
{
"extends": "./tsconfig.paths.json",
"compilerOptions": {
"lib": ["ESNext"],
"moduleResolution": "node",
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": true,
"strictNullChecks": true,
"sourceMap": true,
"target": "ES2020",
"outDir": "lib"
},
"include": ["src/**/*.ts", "serverless.ts"],
"exclude": [
"node_modules/**/*",
".serverless/**/*",
".webpack/**/*",
"_warmup/**/*",
".vscode/**/*"
],
"ts-node": {
"require": ["tsconfig-paths/register"]
}
}我编辑了模板生成的处理程序,以验证请求是否具有名为id的非空路径参数。
import middy from '@middy/core'
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'
async function lambdaHandler(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> {
if (event.pathParameters === null || event.pathParameters.id === null) {
throw new Error("id path parameter is required but is null")
}
return {
statusCode: 200,
body: `Hello ${event.pathParameters.id} from ${event.path}`
}
}
let handler = middy(lambdaHandler)
export default handler如何使用Middy的验证器中间件来执行此验证?
发布于 2022-06-17 06:40:07
@middy/validator是ajv的包装器,它使用JSON。
您的eventSchema可能如下所示:
{
"type":"object",
"properties":{
"pathParameters":{
"type":"object",
"properties":{
"id": { "type":"string" }
},
"required":["id"]
}
},
"required":["pathParameters"]
}https://stackoverflow.com/questions/72572518
复制相似问题