Middy 中间件引擎开源项目

我要开发同款
白开水不加糖2021年07月28日
44阅读
开发技术JavaScriptTypeScript
所属分类Node.js扩展、Web应用开发
授权协议MIT

作品详情

Middy是一个非常简单的中间件引擎,可让你在使用Node.js时简化AWSLambda代码。

如果你使用过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}

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论