Luciano Mammino PRO
Cloud developer, entrepreneur, fighter, butterfly maker! #nodejs #javascript - Author of https://www.nodejsdesignpatterns.com , Founder of https://fullstackbulletin.com
Â
Â
Â
Â
Â
Â
The stylish Node.js middleware engine
for AWS Lambda
npm install middy
const middy = require('middy')
const { urlEncodedBodyParser, validator, httpErrorHandler } = require('middy/middlewares')
const processPaymentHandler = (event, context, callback) => {
  const { 
    creditCardNumber,
    expiryMonth,
    expiryYear,
    cvc,
    nameOnCard,
    amount
  } = event.body
  
  // do stuff with this data ...
  
  return callback(null,
    { result: 'success', message: 'payment processed correctly'}
  )
}
const inputSchema = {
 // define validation schema here ...
}
const handler = middy(processPaymentHandler)
  .use(urlEncodedBodyParser())
  .use(validator(inputSchema))
  .use(httpErrorHandler())
module.exports = { handler }Handler
Attach middlewares
Export enhanced handler
const middy = require('middy')
const { middleware1, middleware2, middleware3 } = require('middy/middlewares')
const originalHandler = (event, context, callback) => {
  /* your business logic */
}
const handler = middy(originalHandler)
handler
  .use(middleware1())
  .use(middleware2())
  .use(middleware3())
module.exports = { handler }1. define handler
2. "middify" handler
3. attach middlewares
4. export "middyfied" handler
const myMiddleware = (config) => {
  
  // might set default options in config
  
  return ({
    before: (handler, next) => {
      // might read options from `config`
    },
    after: (handler, next) => {
      // might read options from `config`
    },
    onError: (handler, next) => {
      // might read options from `config`
    }
  })
}
module.exports = myMiddlewareconst 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 }Json Body Parser
Url Encoded Body Parser
Validator
HTTP Error Handler
(for now!)
By Luciano Mammino
Introducing Middy: 🛵 The stylish Node.js middleware engine for AWS Lambda
Cloud developer, entrepreneur, fighter, butterfly maker! #nodejs #javascript - Author of https://www.nodejsdesignpatterns.com , Founder of https://fullstackbulletin.com