Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

344 lines · 9.6 KiB · TypeScript

Last changed by

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

History of this file

Take it

The walk stopped after 200 commits: lines older than 4c4c4ee point at it.

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 1–24why, one step back
1// @denoify-ignore
2import crypto from 'crypto'3import type { Hono } from '../../hono'4import type { Env, Schema } from '../../types'56import { encodeBase64 } from '../../utils/encode'7import type {8 ApiGatewayRequestContext,9 ApiGatewayRequestContextV2,10 ALBRequestContext,11} from './custom-context'12import type { LambdaContext } from './types'1314// eslint-disable-next-line @typescript-eslint/ban-ts-comment15// @ts-ignore16globalThis.crypto ??= crypto1718export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1920// When calling HTTP API or Lambda directly through function urls21export interface APIGatewayProxyEventV2 {22 version: string23 routeKey: string24 headers: Record<string, string | undefined>

fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8

line 25why, one step back
25 multiValueHeaders?: undefined

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 26–66why, one step back
26 cookies?: string[]
27 rawPath: string28 rawQueryString: string29 body: string | null30 isBase64Encoded: boolean31 requestContext: ApiGatewayRequestContextV232 queryStringParameters?: {33 [name: string]: string | undefined34 }35 pathParameters?: {36 [name: string]: string | undefined37 }38 stageVariables?: {39 [name: string]: string | undefined40 }41}4243// When calling Lambda through an API Gateway44export interface APIGatewayProxyEvent {45 version: string46 httpMethod: string47 headers: Record<string, string | undefined>48 multiValueHeaders?: {49 [headerKey: string]: string[]50 }51 path: string52 body: string | null53 isBase64Encoded: boolean54 queryStringParameters?: Record<string, string | undefined>55 requestContext: ApiGatewayRequestContext56 resource: string57 multiValueQueryStringParameters?: {58 [parameterKey: string]: string[]59 }60 pathParameters?: Record<string, string>61 stageVariables?: Record<string, string>62}6364// When calling Lambda through an Application Load Balancer65export interface ALBProxyEvent {66 httpMethod: string

fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8

lines 67–68why, one step back
67 headers?: Record<string, string | undefined>
68 multiValueHeaders?: Record<string, string[] | undefined>

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 69–114why, one step back
69 path: string
70 body: string | null71 isBase64Encoded: boolean72 queryStringParameters?: Record<string, string | undefined>73 requestContext: ALBRequestContext74}7576export interface APIGatewayProxyResult {77 statusCode: number78 statusDescription?: string79 body: string80 headers: Record<string, string>81 cookies?: string[]82 multiValueHeaders?: {83 [headerKey: string]: string[]84 }85 isBase64Encoded: boolean86}8788const getRequestContext = (89 event: LambdaEvent90): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {91 return event.requestContext92}9394const streamToNodeStream = async (95 reader: ReadableStreamDefaultReader<Uint8Array>,96 writer: NodeJS.WritableStream97) => {98 let readResult = await reader.read()99 while (!readResult.done) {100 writer.write(readResult.value)101 readResult = await reader.read()102 }103 writer.end()104}105106export const streamHandle = <107 E extends Env = Env,108 S extends Schema = {},109 BasePath extends string = '/'110>(111 app: Hono<E, S, BasePath>112) => {113 return awslambda.streamifyResponse(114 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 115why, one step back
115 const processor = getProcessor(event)

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 116why, one step back
116 try {

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 117why, one step back
117 const req = processor.createRequest(event)

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 118–131why, one step back
118 const requestContext = getRequestContext(event)
119120 const res = await app.fetch(req, {121 event,122 requestContext,123 context,124 })125126 // Check content type127 const httpResponseMetadata = {128 statusCode: res.status,129 headers: Object.fromEntries(res.headers.entries()),130 }131

fix(aws-lambda): handle response without body (#2401) (#2413)Markus Wolfbefore adoptionf590d0f

lines 132–134why, one step back
132 // Update response stream
133 responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)134

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 135why, one step back
135 if (res.body) {

fix(aws-lambda): handle response without body (#2401) (#2413)Markus Wolfbefore adoptionf590d0f

lines 136–138why, one step back
136 await streamToNodeStream(res.body.getReader(), responseStream)
137 } else {138 responseStream.write('')

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 139–159why, one step back
139 }
140 } catch (error) {141 console.error('Error processing request:', error)142 responseStream.write('Internal Server Error')143 } finally {144 responseStream.end()145 }146 }147 )148}149150/**151 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)152 */153export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(154 app: Hono<E, S, BasePath>155) => {156 return async (157 event: LambdaEvent,158 lambdaContext?: LambdaContext159 ): Promise<APIGatewayProxyResult> => {

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 160–162why, one step back
160 const processor = getProcessor(event)
161162 const req = processor.createRequest(event)

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 163–170why, one step back
163 const requestContext = getRequestContext(event)
164165 const res = await app.fetch(req, {166 event,167 requestContext,168 lambdaContext,169 })170

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 171why, one step back
171 return processor.createResult(event, res)

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 172–174why, one step back
172 }
173}174

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 175–176why, one step back
175abstract class EventProcessor<E extends LambdaEvent> {
176 protected abstract getPath(event: E): string

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 177why, one step back
177

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 178why, one step back
178 protected abstract getMethod(event: E): string

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 179why, one step back
179

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 180why, one step back
180 protected abstract getQueryString(event: E): string

refactor(lambda): aws lambda createResult method (#2038)Aris Kemperbefore adoption0800acc

line 181why, one step back
181

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 182–223why, one step back
182 protected abstract getCookies(event: E, headers: Headers): void
183184 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)

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 224–225why, one step back
224 }
225

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 226–228why, one step back
226 async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {
227 const contentType = res.headers.get('content-type')228 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 229why, one step back
229

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 230–233why, one step back
230 if (!isBase64Encoded) {
231 const contentEncoding = res.headers.get('content-encoding')232 isBase64Encoded = isContentEncodingBinary(contentEncoding)233 }

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 234why, one step back
234

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 235why, one step back
235 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 236why, one step back
236

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 237–241why, one step back
237 const result: APIGatewayProxyResult = {
238 body: body,239 headers: {},240 statusCode: res.status,241 isBase64Encoded,

fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8

line 242why, one step back
242 }

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 243–249why, one step back
243
244 this.setCookies(event, res, result)245 res.headers.forEach((value, key) => {246 result.headers[key] = value247 })248249 return result

fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8

line 250why, one step back
250 }

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 251–257why, one step back
251
252 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')

fix(adapter): handle multi value headers in AWS Lambda (#2494)TATSUNO “Taz” Yasuhirobefore adoptionacb56b8

line 258why, one step back
258 }

chore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9

line 259why, one step back
259 }

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 260why, one step back
260 }

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 261why, one step back
261}

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 262why, one step back
262

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 263–265why, one step back
263const v2Processor = new (class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {
264 protected getPath(event: APIGatewayProxyEventV2): string {265 return event.rawPath

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 266–267why, one step back
266 }
267

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 268–269why, one step back
268 protected getMethod(event: APIGatewayProxyEventV2): string {
269 return event.requestContext.http.method

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 270–271why, one step back
270 }
271

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 272–274why, one step back
272 protected getQueryString(event: APIGatewayProxyEventV2): string {
273 return event.rawQueryString274 }

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 275why, one step back
275

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 276–280why, one step back
276 protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {
277 if (Array.isArray(event.cookies)) {278 headers.set('Cookie', event.cookies.join('; '))279 }280 }

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 281why, one step back
281

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 282–283why, one step back
282 protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {
283 result.cookies = cookies

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 284why, one step back
284 }

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

line 285why, one step back
285})()

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 286why, one step back
286

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 287–316why, one step back
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,

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

line 317why, one step back
317 }

refactor(aws-lambda): replace conditional logics with polymorphism (#2521)TATSUNO “Taz” Yasuhirobefore adoptionc83d80f

lines 318–325why, one step back
318 }
319})()320321const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {322 if (isProxyEventV2(event)) {323 return v2Processor324 } else {325 return v1Processor

fix(context): set `status` correctly (#1814)Yusuke Wadabefore adoption4c4c4ee

lines 326–344why, one step back
326 }
327}328329const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {330 return Object.prototype.hasOwnProperty.call(event, 'rawPath')331}332333export const isContentTypeBinary = (contentType: string) => {334 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(335 contentType336 )337}338339export const isContentEncodingBinary = (contentEncoding: string | null) => {340 if (contentEncoding === null) {341 return false342 }343 return /^(gzip|deflate|compress|br)/.test(contentEncoding)344}