Reputation: 1
I'm using middy. I have a lambda function which serves 4 routes. The routes map to one index.handler. Middy http router is used to route to the subsequent handler for that path. The each handler has a different validator, but it seems like all the validator gets executed for each route regardless if it has a validator or not. In this code, getBookhandler will fail validation even though no validator is assigned.
I think the behavior is not correct, but maybe I misunderstand it.
import middy from '@middy/core';
import httpRouterHandler, { Route } from '@middy/http-router';
import httpHeaderNormalizer from '@middy/http-header-normalizer';
import validator from '@middy/validator';
import { transpileSchema } from '@middy/validator/transpile';
import { Context, APIGatewayProxyResult, APIGatewayEvent } from 'aws-lambda';
const eventSchema = {
type: 'object',
required: ['body','foo'],
properties: {
// this will pass validation
body: {
type: 'string'
},
}
};
const getBookHandler = middy()
.use(httpHeaderNormalizer())
.handler((event:APIGatewayEvent, context) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'get Book',
}),
}
})
const postBookHandler = middy()
.use(
validator({
eventSchema: transpileSchema(eventSchema)
})
)
.handler((event:APIGatewayEvent, context) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'post Book',
}),
}
})
const postBookContentHandler = middy()
.use(httpHeaderNormalizer())
.handler((event:APIGatewayEvent, context) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'post Book Content',
}),
}
})
const routes: Route[] = [
{
method: 'GET',
path: '/book',
handler: getBookHandler
},
{
method: 'POST',
path: '/book',
handler: postBookHandler
},
{
method: 'POST',
path: '/book/contents',
handler: postBookContentHandler
}
];
export const handler = middy()
.use(httpHeaderNormalizer()) // Apply httpHeaderNormalizer to the main handler
.handler(httpRouterHandler(routes));
Environment:
Node v16.19.0
"devDependencies": {
"@types/aws-lambda": "^8.10.121",
"esbuild": "^0.19.3"
},
"dependencies": {
"@middy/core": "^4.6.4",
"@middy/http-header-normalizer": "^4.6.4",
"@middy/http-router": "^4.6.4",
"@middy/validator": "^4.6.4"
}`
I would expect that the validator would apply to the handler I set it to and not all handlers
Upvotes: 0
Views: 479
Reputation: 1
Issue is addressed here: https://github.com/middyjs/middy/issues/1107
Setting validator strict: false avoids all handlers failing.
Upvotes: 0