Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

271 lines · 7.4 KiB · TypeScript

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 731957a point at it.

v3.7.2Yusuke Wadabefore adoption731957a

lines 1–6why, 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'

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 7–11why, one step back
7import type {
8 ApiGatewayRequestContext,9 ApiGatewayRequestContextV2,10 ALBRequestContext,11} from './custom-context'

feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0

line 12why, one step back
12import type { LambdaContext } from './types'

v3.7.2Yusuke Wadabefore adoption731957a

lines 13–17why, one step back
13
14// eslint-disable-next-line @typescript-eslint/ban-ts-comment15// @ts-ignore16globalThis.crypto ??= crypto17

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 18–20why, one step back
18export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent
1920// When calling HTTP API or Lambda directly through function urls

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

line 21why, one step back
21export interface APIGatewayProxyEventV2 {

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 22–23why, one step back
22 version: string
23 routeKey: string

v3.7.2Yusuke Wadabefore adoption731957a

line 24why, one step back
24 headers: Record<string, string | undefined>

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

line 25why, one step back
25 cookies?: string[]

v3.7.2Yusuke Wadabefore adoption731957a

lines 26–29why, one step back
26 rawPath: string
27 rawQueryString: string28 body: string | null29 isBase64Encoded: boolean

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 30–39why, one step back
30 requestContext: ApiGatewayRequestContextV2
31 queryStringParameters?: {32 [name: string]: string | undefined33 }34 pathParameters?: {35 [name: string]: string | undefined36 }37 stageVariables?: {38 [name: string]: string | undefined39 }

v3.7.2Yusuke Wadabefore adoption731957a

lines 40–41why, one step back
40}
41

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 42why, one step back
42// When calling Lambda through an API Gateway

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

line 43why, one step back
43export interface APIGatewayProxyEvent {

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 44why, one step back
44 version: string

v3.7.2Yusuke Wadabefore adoption731957a

lines 45–46why, one step back
45 httpMethod: string
46 headers: Record<string, string | undefined>

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

lines 47–49why, one step back
47 multiValueHeaders?: {
48 [headerKey: string]: string[]49 }

v3.7.2Yusuke Wadabefore adoption731957a

lines 50–54why, one step back
50 path: string
51 body: string | null52 isBase64Encoded: boolean53 queryStringParameters?: Record<string, string | undefined>54 requestContext: ApiGatewayRequestContext

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 55–60why, one step back
55 resource: string
56 multiValueQueryStringParameters?: {57 [parameterKey: string]: string[]58 }59 pathParameters?: Record<string, string>60 stageVariables?: Record<string, string>

v3.7.2Yusuke Wadabefore adoption731957a

lines 61–62why, one step back
61}
62

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 63–65why, one step back
63// When calling Lambda through an Application Load Balancer
64export interface ALBProxyEvent {65 httpMethod: string

v3.7.2Yusuke Wadabefore adoption731957a

line 66why, one step back
66 headers: Record<string, string | undefined>

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 67why, one step back
67 path: string

v3.7.2Yusuke Wadabefore adoption731957a

lines 68–69why, one step back
68 body: string | null
69 isBase64Encoded: boolean

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 70–71why, one step back
70 queryStringParameters?: Record<string, string | undefined>
71 requestContext: ALBRequestContext

v3.7.2Yusuke Wadabefore adoption731957a

lines 72–73why, one step back
72}
73

fix(aws-lambda): export `APIGatewayProxyResult` (#1711)juhobefore adoption0a2b54a

line 74why, one step back
74export interface APIGatewayProxyResult {

v3.7.2Yusuke Wadabefore adoption731957a

line 75why, one step back
75 statusCode: number

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 76why, one step back
76 statusDescription?: string

v3.7.2Yusuke Wadabefore adoption731957a

lines 77–78why, one step back
77 body: string
78 headers: Record<string, string>

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

lines 79–82why, one step back
79 cookies?: string[]
80 multiValueHeaders?: {81 [headerKey: string]: string[]82 }

v3.7.2Yusuke Wadabefore adoption731957a

lines 83–86why, one step back
83 isBase64Encoded: boolean
84}8586const getRequestContext = (

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 87–88why, one step back
87 event: LambdaEvent
88): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {

v3.7.2Yusuke Wadabefore adoption731957a

line 89why, one step back
89 return event.requestContext

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

lines 90–111why, one step back
90}
9192const streamToNodeStream = async (93 reader: ReadableStreamDefaultReader<Uint8Array>,94 writer: NodeJS.WritableStream95) => {96 let readResult = await reader.read()97 while (!readResult.done) {98 writer.write(readResult.value)99 readResult = await reader.read()100 }101 writer.end()102}103104export const streamHandle = <105 E extends Env = Env,106 S extends Schema = {},107 BasePath extends string = '/'108>(109 app: Hono<E, S, BasePath>110) => {111 return awslambda.streamifyResponse(

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 112why, one step back
112 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

lines 113–117why, one step back
113 try {
114 const req = createRequest(event)115 const requestContext = getRequestContext(event)116117 const res = await app.fetch(req, {

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 118why, one step back
118 event,

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

lines 119–142why, one step back
119 requestContext,
120 context,121 })122123 // Check content type124 const httpResponseMetadata = {125 statusCode: res.status,126 headers: Object.fromEntries(res.headers.entries()),127 }128129 if (res.body) {130 await streamToNodeStream(131 res.body.getReader(),132 awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)133 )134 }135 } catch (error) {136 console.error('Error processing request:', error)137 responseStream.write('Internal Server Error')138 } finally {139 responseStream.end()140 }141 }142 )

v3.7.2Yusuke Wadabefore adoption731957a

lines 143–151why, one step back
143}
144145/**146 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)147 */148export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(149 app: Hono<E, S, BasePath>150) => {151 return async (

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 152why, one step back
152 event: LambdaEvent,

feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0

line 153why, one step back
153 lambdaContext?: LambdaContext

v3.7.2Yusuke Wadabefore adoption731957a

lines 154–157why, one step back
154 ): Promise<APIGatewayProxyResult> => {
155 const req = createRequest(event)156 const requestContext = getRequestContext(event)157

feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0

line 158why, one step back
158 const res = await app.fetch(req, {

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 159why, one step back
159 event,

feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0

lines 160–162why, one step back
160 requestContext,
161 lambdaContext,162 })

v3.7.2Yusuke Wadabefore adoption731957a

line 163why, one step back
163

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

line 164why, one step back
164 return createResult(event, res)

v3.7.2Yusuke Wadabefore adoption731957a

lines 165–167why, one step back
165 }
166}167

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 168why, one step back
168const createResult = async (event: LambdaEvent, res: Response): Promise<APIGatewayProxyResult> => {

v3.7.2Yusuke Wadabefore adoption731957a

lines 169–176why, one step back
169 const contentType = res.headers.get('content-type')
170 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false171172 if (!isBase64Encoded) {173 const contentEncoding = res.headers.get('content-encoding')174 isBase64Encoded = isContentEncodingBinary(contentEncoding)175 }176

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

lines 177–178why, one step back
177 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()
178

v3.7.2Yusuke Wadabefore adoption731957a

lines 179–185why, one step back
179 const result: APIGatewayProxyResult = {
180 body: body,181 headers: {},182 statusCode: res.status,183 isBase64Encoded,184 }185

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

line 186why, one step back
186 setCookies(event, res, result)

v3.7.2Yusuke Wadabefore adoption731957a

lines 187–193why, one step back
187 res.headers.forEach((value, key) => {
188 result.headers[key] = value189 })190191 return result192}193

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 194why, one step back
194const createRequest = (event: LambdaEvent) => {

v3.7.2Yusuke Wadabefore adoption731957a

line 195why, one step back
195 const queryString = extractQueryString(event)

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 196–201why, one step back
196 const domainName =
197 event.requestContext && 'domainName' in event.requestContext198 ? event.requestContext.domainName199 : event.headers['host']200 const path = isProxyEventV2(event) ? event.rawPath : event.path201 const urlPath = `https://${domainName}${path}`

v3.7.2Yusuke Wadabefore adoption731957a

lines 202–204why, one step back
202 const url = queryString ? `${urlPath}?${queryString}` : urlPath
203204 const headers = new Headers()

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

line 205why, one step back
205 getCookies(event, headers)

v3.7.2Yusuke Wadabefore adoption731957a

line 206why, one step back
206 for (const [k, v] of Object.entries(event.headers)) {

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

lines 207–209why, one step back
207 if (v) {
208 headers.set(k, v)209 }

v3.7.2Yusuke Wadabefore adoption731957a

lines 210–211why, one step back
210 }
211

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 212why, one step back
212 const method = isProxyEventV2(event) ? event.requestContext.http.method : event.httpMethod

v3.7.2Yusuke Wadabefore adoption731957a

lines 213–224why, one step back
213 const requestInit: RequestInit = {
214 headers,215 method,216 }217218 if (event.body) {219 requestInit.body = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body220 }221222 return new Request(url, requestInit)223}224

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

lines 225–231why, one step back
225const extractQueryString = (event: LambdaEvent) => {
226 return isProxyEventV2(event)227 ? event.rawQueryString228 : Object.entries(event.queryStringParameters || {})229 .filter(([, value]) => value)230 .map(([key, value]) => `${key}=${value}`)231 .join('&')

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

lines 232–233why, one step back
232}
233

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 234why, one step back
234const getCookies = (event: LambdaEvent, headers: Headers) => {

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

lines 235–239why, one step back
235 if (isProxyEventV2(event) && Array.isArray(event.cookies)) {
236 headers.set('Cookie', event.cookies.join('; '))237 }238}239

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 240why, one step back
240const setCookies = (event: LambdaEvent, res: Response, result: APIGatewayProxyResult) => {

fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375

lines 241–253why, one step back
241 if (res.headers.has('set-cookie')) {
242 const cookies = res.headers.get('set-cookie')?.split(', ')243 if (Array.isArray(cookies)) {244 if (isProxyEventV2(event)) {245 result.cookies = cookies246 } else {247 result.multiValueHeaders = {248 'set-cookie': cookies,249 }250 }251 res.headers.delete('set-cookie')252 }253 }

v3.7.2Yusuke Wadabefore adoption731957a

lines 254–255why, one step back
254}
255

Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c

line 256why, one step back
256const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {

v3.7.2Yusuke Wadabefore adoption731957a

lines 257–260why, one step back
257 return Object.prototype.hasOwnProperty.call(event, 'rawPath')
258}259260export const isContentTypeBinary = (contentType: string) => {

fix: add missing tail to svg regex (#1788)Elias Brangebefore adoption521db64

line 261why, one step back
261 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(

v3.7.2Yusuke Wadabefore adoption731957a

lines 262–271why, one step back
262 contentType
263 )264}265266export const isContentEncodingBinary = (contentEncoding: string | null) => {267 if (contentEncoding === null) {268 return false269 }270 return /^(gzip|deflate|compress|br)/.test(contentEncoding)271}