쵸 와카르 middy
15972 단어 middy람다middleware자바스크립트
middy라는 모르는 사람이 있었으므로, 조금 조사해 본다
음 거의 이하의 공식 문서를 일본어 번역해, 이해하기 어려운 곳을 바꿔 말한 느낌
htps : // 미 dy. js. rg/
이용 예
공식 문서에 실린 지불 처리 API의 예
//# 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
// ...
return { result: 'success', message: 'payment processed correctly'}
}
// 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 }
구현 방법
import middy from '@middy/core'
import middleware1 from 'sample-middleware1'
import middleware2 from 'sample-middleware2'
import middleware3 from 'sample-middleware3'
const baseHandler = (event, context) => {
/* your business logic */
}
const handler = middy(baseHandler)
handler
.use(middleware1())
.use(middleware2())
.use(middleware3())
module.exports = { handler }
//# 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
// ...
return { result: 'success', message: 'payment processed correctly'}
}
// 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 }
import middy from '@middy/core'
import middleware1 from 'sample-middleware1'
import middleware2 from 'sample-middleware2'
import middleware3 from 'sample-middleware3'
const baseHandler = (event, context) => {
/* your business logic */
}
const handler = middy(baseHandler)
handler
.use(middleware1())
.use(middleware2())
.use(middleware3())
module.exports = { handler }
위에서 언급했듯이 세 개의 미들웨어가 호출되면 비즈니스 로직을 래핑 한 핸들러를 포함하여 다음과 같은 실행 순서가됩니다.
공식 문서에서는 "양파와 같은 미들웨어 패턴"이라고합니다.
미들웨어 구현
middy가 준비하고 있는 미들웨어( 여기 의 Available middlewares 참조)는 있지만, 미들웨어를 스스로 구현하는 것도 가능
샘플 코드
// customMiddleware.js
const defaults = {}
module.exports = (opts = {}) => {
const options = { ...defaults, ...opts }
const customMiddlewareBefore = async (request) => {
// might read options
}
const customMiddlewareAfter = async (request) => {
// might read options
}
const customMiddlewareOnError = async (request) => {
// might read options
}
return {
// Having descriptive function names will allow for easier tracking of perormance bottlenecks using @middy/core/profiler
before: customMiddlewareBefore,
after: customMiddlewareAfter,
onError: customMiddlewareOnError
}
}
미들웨어는
// customMiddleware.js
const defaults = {}
module.exports = (opts = {}) => {
const options = { ...defaults, ...opts }
const customMiddlewareBefore = async (request) => {
// might read options
}
const customMiddlewareAfter = async (request) => {
// might read options
}
const customMiddlewareOnError = async (request) => {
// might read options
}
return {
// Having descriptive function names will allow for easier tracking of perormance bottlenecks using @middy/core/profiler
before: customMiddlewareBefore,
after: customMiddlewareAfter,
onError: customMiddlewareOnError
}
}
세 가지 키 중 적어도 하나를 반환해야합니다.
재사용하지 않는 미들웨어는 인라인 미들웨어라고 하는 형태로, 비즈니스 로직과 같은 클래스에 기재할 수도 있다.
import middy from '@middy/core'
const handler = middy((event, context) => {
// do stuff
})
handler.before(async (request) => {
// do something in the before phase
})
handler.after(async (request) => {
// do something in the after phase
})
handler.onError(async (request) => {
// do something in the on error phase
})
module.exports = { handler }
Reference
이 문제에 관하여(쵸 와카르 middy), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/10inoino/items/03509932f1ee4108ef52텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)