如果你使用过Express等Web框架,那么你将熟悉Middy中采用的概念,你将能够很快上手。
中间件引擎允许你专注于Lambda的严格业务逻辑,然后通过装饰主要业务逻辑,以模块化和可重用的方式附加额外的通用元素,如认证、授权、验证、序列化等。
//#handler.js#//importcoreimportmiddyfrom'@middy/core'//esmNodev14+//constmiddy=require('@middy/core')//commonjsNodev12+//importsomemiddlewaresimportjsonBodyParserfrom'@middy/http-json-body-parser'importhttpErrorHandlerfrom'@middy/http-error-handler'importvalidatorfrom'@middy/validator'//Thisisyourcommonhandler,innowaydifferentthanwhatyouareusedtodoingeverydayinAWSLambdaconstbaseHandler=async(event,context,callback)=>{//wedon'tneedtodeserializethebodyourselfasamiddlewarewillbeusedtodothatconst{creditCardNumber,expiryMonth,expiryYear,cvc,nameOnCard,amount}=event.body//dostuffwiththisdata//...constresponse={result:'success',message:'paymentprocessedcorrectly'}return{statusCode:200,body:JSON.stringify(response)}}//Noticethatinthehandleryouonlyaddedbasebusinesslogic(nodeserialization,//validationorerrorhandler),wewilladdtherestwithmiddlewaresconstinputSchema={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']//Inserthereallrequiredeventproperties}}}//Let's"middyfy"ourhandler,thenwewillbeabletoattachmiddlewarestoitconsthandler=middy(baseHandler).use(jsonBodyParser())//parsestherequestbodywhenit'saJSONandconvertsittoanobject.use(validator({inputSchema}))//validatestheinput.use(httpErrorHandler())//handlescommonhttperrorsandreturnsproperresponsesmodule.exports={handler}
评论