Skip to content
Myr

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by TATSUNO “Taz” Yasuhiro · committed by GitHub · parent fa9ed80 · Browse files · 1 file+134 added−74 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+134 added−74 removed

  • other:+134 added−74 removed

1 file+134 added−74 removed

modified:src/adapter/aws-lambda/handler.ts+134 added-74 removed
110 unmodified lines
111 app: Hono<E, S, BasePath>112) => {113 return awslambda.streamifyResponse(114 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {115 const processor = getProcessor(event)116 try {116 const req = createRequest(event)117 const req = processor.createRequest(event)118 const requestContext = getRequestContext(event)119120 const res = await app.fetch(req, {121 event,
34 unmodified lines
156 return async (157 event: LambdaEvent,158 lambdaContext?: LambdaContext159 ): Promise<APIGatewayProxyResult> => {159 const req = createRequest(event)160 const processor = getProcessor(event)161162 const req = processor.createRequest(event)163 const requestContext = getRequestContext(event)164165 const res = await app.fetch(req, {166 event,167 requestContext,168 lambdaContext,169 })170168 return createResult(event, res)171 return processor.createResult(event, res)172 }173}174172const createResult = async (event: LambdaEvent, res: Response): Promise<APIGatewayProxyResult> => {173 const contentType = res.headers.get('content-type')174 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false175abstract class EventProcessor<E extends LambdaEvent> {176 protected abstract getPath(event: E): string177176 if (!isBase64Encoded) {177 const contentEncoding = res.headers.get('content-encoding')178 isBase64Encoded = isContentEncodingBinary(contentEncoding)179 }178 protected abstract getMethod(event: E): string179181 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()180 protected abstract getQueryString(event: E): string181183 const result: APIGatewayProxyResult = {184 body: body,185 headers: {},186 statusCode: res.status,187 isBase64Encoded,182 protected abstract getCookies(event: E, headers: Headers): void183184 protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void185186 createRequest(event: E): Request {187 const queryString = this.getQueryString(event)188 const domainName =189 event.requestContext && 'domainName' in event.requestContext190 ? event.requestContext.domainName191 : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]192 const path = this.getPath(event)193 const urlPath = `https://${domainName}${path}`194 const url = queryString ? `${urlPath}?${queryString}` : urlPath195196 const headers = new Headers()197 this.getCookies(event, headers)198 if (event.headers) {199 for (const [k, v] of Object.entries(event.headers)) {200 if (v) {201 headers.set(k, v)202 }203 }204 }205 if (event.multiValueHeaders) {206 for (const [k, values] of Object.entries(event.multiValueHeaders)) {207 if (values) {208 values.forEach((v) => headers.append(k, v))209 }210 }211 }212213 const method = this.getMethod(event)214 const requestInit: RequestInit = {215 headers,216 method,217 }218219 if (event.body) {220 requestInit.body = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body221 }222223 return new Request(url, requestInit)224 }225190 setCookies(event, res, result)191 res.headers.forEach((value, key) => {192 result.headers[key] = value193 })226 async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {227 const contentType = res.headers.get('content-type')228 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false229195 return result196}230 if (!isBase64Encoded) {231 const contentEncoding = res.headers.get('content-encoding')232 isBase64Encoded = isContentEncodingBinary(contentEncoding)233 }234198const createRequest = (event: LambdaEvent) => {199 const queryString = extractQueryString(event)200 const domainName =201 event.requestContext && 'domainName' in event.requestContext202 ? event.requestContext.domainName203 : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]204 const path = isProxyEventV2(event) ? event.rawPath : event.path205 const urlPath = `https://${domainName}${path}`206 const url = queryString ? `${urlPath}?${queryString}` : urlPath235 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()236208 const headers = new Headers()209 getCookies(event, headers)210 if (event.headers) {211 for (const [k, v] of Object.entries(event.headers)) {212 if (v) {213 headers.set(k, v)214 }237 const result: APIGatewayProxyResult = {238 body: body,239 headers: {},240 statusCode: res.status,241 isBase64Encoded,242 }243244 this.setCookies(event, res, result)245 res.headers.forEach((value, key) => {246 result.headers[key] = value247 })248249 return result250 }217 if (event.multiValueHeaders) {218 for (const [k, values] of Object.entries(event.multiValueHeaders)) {219 if (values) {220 values.forEach((v) => headers.append(k, v))251252 setCookies = (event: LambdaEvent, res: Response, result: APIGatewayProxyResult) => {253 if (res.headers.has('set-cookie')) {254 const cookies = res.headers.get('set-cookie')?.split(', ')255 if (Array.isArray(cookies)) {256 this.setCookiesToResult(result, cookies)257 res.headers.delete('set-cookie')258 }259 }260 }261}262225 const method = isProxyEventV2(event) ? event.requestContext.http.method : event.httpMethod226 const requestInit: RequestInit = {227 headers,228 method,263const v2Processor = new (class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {264 protected getPath(event: APIGatewayProxyEventV2): string {265 return event.rawPath266 }267231 if (event.body) {232 requestInit.body = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body268 protected getMethod(event: APIGatewayProxyEventV2): string {269 return event.requestContext.http.method270 }271272 protected getQueryString(event: APIGatewayProxyEventV2): string {235 return new Request(url, requestInit)236}273 return event.rawQueryString274 }275238const extractQueryString = (event: LambdaEvent) => {239 return isProxyEventV2(event)240 ? event.rawQueryString241 : Object.entries(event.queryStringParameters || {})242 .filter(([, value]) => value)243 .map(([key, value]) => `${key}=${value}`)244 .join('&')245}276 protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {277 if (Array.isArray(event.cookies)) {278 headers.set('Cookie', event.cookies.join('; '))279 }280 }281247const getCookies = (event: LambdaEvent, headers: Headers) => {248 if (isProxyEventV2(event) && Array.isArray(event.cookies)) {249 headers.set('Cookie', event.cookies.join('; '))282 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {283 result.cookies = cookies284 }251}285})()286253const setCookies = (event: LambdaEvent, res: Response, result: APIGatewayProxyResult) => {254 if (res.headers.has('set-cookie')) {255 const cookies = res.headers.get('set-cookie')?.split(', ')256 if (Array.isArray(cookies)) {257 if (isProxyEventV2(event)) {258 result.cookies = cookies259 } else {260 result.multiValueHeaders = {261 'set-cookie': cookies,262 }263 }264 res.headers.delete('set-cookie')287const v1Processor = new (class EventV1Processor extends EventProcessor<288 Exclude<LambdaEvent, APIGatewayProxyEventV2>289> {290 protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {291 return event.path292 }293294 protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {295 return event.httpMethod296 }297298 protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {299 return Object.entries(event.queryStringParameters || {})300 .filter(([, value]) => value)301 .map(([key, value]) => `${key}=${value}`)302 .join('&')303 }304305 protected getCookies(306 // eslint-disable-next-line @typescript-eslint/no-unused-vars307 event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,308 // eslint-disable-next-line @typescript-eslint/no-unused-vars309 headers: Headers310 ): void {311 // nop312 }313314 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {315 result.multiValueHeaders = {316 'set-cookie': cookies,317 }318 }319})()320321const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {322 if (isProxyEventV2(event)) {323 return v2Processor324 } else {325 return v1Processor326 }327}328329const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {330 return Object.prototype.hasOwnProperty.call(event, 'rawPath')
14 unmodified lines