I created a brand new project using the TypeScript template:
$ serverless create --template aws-nodejs-typescript --path demo
I edited tsconfig.json
and enabled strictNullChecks
as I prefer this feature to be turned on:
{
"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"]
}
}
I edited the handler that is generated by the template a bit to validate that the request has a non-null path parameter named 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
How can I use Middy's validator middleware to perform this validation instead?
@middy/validator
is a wrapper aroundajv
which uses JSON Schema.Your
eventSchema
might look like this: