This handler can route to requests to one of a nested hander based on method
and path
of an http event from API Gateway (REST or HTTP) or Elastic Load Balancer.
Install
To install this middleware you can use NPM:
npm install --save @middy/http-router
Options
routes
(array[{method, path, handler}]) (required): Array of route objects.
method
(string) (required): One of GET
, POST
, PUT
, PATCH
, DELETE
, OPTIONS
and ANY
that will match to any method passed inpath
(string) (required): AWS formatted path starting with /
. Variable: /{id}/
, Wildcard: /{proxy+}
handler
(function) (required): Any handler(event, context)
function
NOTES:
- Errors should be handled as part of the router middleware stack or the lambdaHandler middleware stack. Handled errors in the later will trigger the
after
middleware stack of the former. - Shared middlewares, connected to the router middleware stack, can only be run before the lambdaHandler middleware stack.
Sample usage
import middy from '@middy/core'
import validatorMiddleware from '@middy/validator'
const getHandler = middy()
.use(validatorMiddleware({eventSchema: {...} }))
.handler((event, context) => {
return {
statusCode: 200,
body: '{...}'
}
})
const postHandler = middy()
.use(validatorMiddleware({eventSchema: {...} }))
.handler((event, context) => {
return {
statusCode: 200,
body: '{...}'
}
})
handler = middy()
.use(httpHeaderNormalizer())
.handler(httpRouterHandler([
{
method: 'GET',
path: '/user/{id}',
handler: getHandler
},
{
method: 'POST',
path: '/user',
handler: postHandler
}
]))
module.exports = { handler }
Middy documentation and examples
For more documentation and examples, refers to the main Middy monorepo on GitHub or Middy official website.
Contributing
Everyone is very welcome to contribute to this repository. Feel free to raise issues or to submit Pull Requests.
License
Licensed under MIT License. Copyright (c) 2017-2022 Luciano Mammino, will Farrell, and the Middy team.