One of the main strengths of serverless and AWS Lambda is that, from a developer perspective, your focus is mostly shifted toward implementing business logic. Anyway, when you are writing an handler, you still have to deal with some common technical concerns outside business logic, like input parsing and validation, output serialization, error handling, etc. Very often, all this necessary code ends up polluting the pure business logic code in your handlers, making the code harder to read and to maintain. In other contexts, like generic web frameworks (express, fastify, hapi, etc.), this problem has been solved using the middleware pattern. Middy brings the middleware pattern into AWS Lambda making it easier to focus on business logic and reuse the boilerplate code across different functions.
5. exports.myLambda = function (
event,
context,
callback
) {
// get input from event and context
// use callback to return output or errors
}
Anatomy of a Node.js lambda on AWS
5
6. (event, context, callback) => {
// decrypt environment variables with KMS
// deserialize the content of the event
// validate input, authentication, authorization
// REAL BUSINESS LOGIC
// (process input, generate output)
// validate output
// serialize response
// handle errors
}
A typical "REAL" Lambda function
LOTS of BOILERPLATE 😓😓
6
14. When an error happens...
Flow is stopped
First middleware implementing `onError` gets control
It can choose to handle the error, or delegate it to the next handler
If the error is handler a response is returned
If the error is not handled the execution fails reporting the unhandled error
14
16. Inline middlewares
const middy = require('middy')
const handler = middy((event, context, callback) => {
// do stuff
})
handler.before((handler, next) => {
// do something in the before phase
next()
})
handler.after((handler, next) => {
// do something in the after phase
next()
})
handler.onError((handler, next) => {
// do something in the on error phase
next()
})
module.exports = { handler }
16
17. Currently availble middlewares
JSON Body Parser
Url Encoded Body Parser
Validator
HTTP Error Handler
CORS
S3 Key Normalizer
Do Not Wait for event loop
Support for async/await handlers (just return, don't need to use callback)
XML Body parser
API Gateway Event normalizer
In development
17