Middy 是一个非常简单的中间件引擎,可让你在使用 Node.js 时简化 AWS Lambda 代码。
如果你使用过 Express 等 Web 框架,那么你将熟悉 Middy 中采用的概念,你将能够很快上手。
中间件引擎允许你专注于 Lambda 的严格业务逻辑,然后通过装饰主要业务逻辑,以模块化和可重用的方式附加额外的通用元素,如认证、授权、验证、序列化等。
//# handler.js # // import core import middy from '@middy/core' // esm Node v14+ //const middy = require('@middy/core') // commonjs Node v12+ // import some middlewares import jsonBodyParser from '@middy/http-json-body-parser' import httpErrorHandler from '@middy/http-error-handler' import validator from '@middy/validator' // This is your common handler, in no way different than what you are used to doing every day in AWS Lambda const baseHandler = async (event, context, callback) => { // we don't need to deserialize the body ourself as a middleware will be used to do that const { creditCardNumber, expiryMonth, expiryYear, cvc, nameOnCard, amount } = event.body // do stuff with this data // ... const response = { result: 'success', message: 'payment processed correctly'} return {statusCode: 200, body: JSON.stringify(response)} } // Notice that in the handler you only added base business logic (no deserialization, // validation or error handler), we will add the rest with middlewares const inputSchema = { type: 'object', properties: { body: { type: 'object', properties: { creditCardNumber: { type: 'string', minLength: 12, maxLength: 19, pattern: '\d+' }, expiryMonth: { type: 'integer', minimum: 1, maximum: 12 }, expiryYear: { type: 'integer', minimum: 2017, maximum: 2027 }, cvc: { type: 'string', minLength: 3, maxLength: 4, pattern: '\d+' }, nameOnCard: { type: 'string' }, amount: { type: 'number' } }, required: ['creditCardNumber'] // Insert here all required event properties } } } // Let's "middyfy" our handler, then we will be able to attach middlewares to it const handler = middy(baseHandler) .use(jsonBodyParser()) // parses the request body when it's a JSON and converts it to an object .use(validator({inputSchema})) // validates the input .use(httpErrorHandler()) // handles common http errors and returns proper responses module.exports = { handler }
评论