Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

272 lines · 7.5 KiB · TypeScript

Last changed by

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

History of this file

Take it

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 1–3why, one step back
1// @denoify-ignore
2import crypto from 'crypto'3import type { Hono } from '../../hono'

fix(types): remove type-errors for routes (#1371)Yusuke Wadabefore adoption6034dd7

line 4why, one step back
4import type { Env, Schema } from '../../types'

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 5–6why, one step back
5
6import { encodeBase64 } from '../../utils/encode'

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)watanybefore adoptioneefdb27

line 7why, one step back
7import type { ApiGatewayRequestContext, LambdaFunctionUrlRequestContext } from './custom-context'

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

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 9–14why, one step back
9
10// eslint-disable-next-line @typescript-eslint/ban-ts-comment11// @ts-ignore12globalThis.crypto ??= crypto1314// When calling Lambda directly through function urls

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

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

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

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 19–22why, one step back
19 rawPath: string
20 rawQueryString: string21 body: string | null22 isBase64Encoded: boolean

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)watanybefore adoptioneefdb27

line 23why, one step back
23 requestContext: ApiGatewayRequestContext

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 24–26why, one step back
24}
2526// When calling Lambda through an API Gateway or an ELB

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

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

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

lines 30–32why, one step back
30 multiValueHeaders?: {
31 [headerKey: string]: string[]32 }

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 33–36why, one step back
33 path: string
34 body: string | null35 isBase64Encoded: boolean36 queryStringParameters?: Record<string, string | undefined>

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)watanybefore adoptioneefdb27

line 37why, one step back
37 requestContext: ApiGatewayRequestContext

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 38–40why, one step back
38}
3940// When calling Lambda through an Lambda Function URLs

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

line 41why, one step back
41export interface LambdaFunctionUrlEvent {

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 42–46why, one step back
42 headers: Record<string, string | undefined>
43 rawPath: string44 rawQueryString: string45 body: string | null46 isBase64Encoded: boolean

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)watanybefore adoptioneefdb27

line 47why, one step back
47 requestContext: LambdaFunctionUrlRequestContext

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 48–53why, one step back
48}
4950interface APIGatewayProxyResult {51 statusCode: number52 body: string53 headers: Record<string, string>

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

lines 54–57why, one step back
54 cookies?: string[]
55 multiValueHeaders?: {56 [headerKey: string]: string[]57 }

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 58–60why, one step back
58 isBase64Encoded: boolean
59}60

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)watanybefore adoptioneefdb27

lines 61–64why, one step back
61const getRequestContext = (
62 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent63): ApiGatewayRequestContext | LambdaFunctionUrlRequestContext => {64 return event.requestContext

Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a

lines 65–120why, one step back
65}
6667const streamToNodeStream = async (68 reader: ReadableStreamDefaultReader<Uint8Array>,69 writer: NodeJS.WritableStream70) => {71 let readResult = await reader.read()72 while (!readResult.done) {73 writer.write(readResult.value)74 readResult = await reader.read()75 }76 writer.end()77}7879export const streamHandle = <80 E extends Env = Env,81 S extends Schema = {},82 BasePath extends string = '/'83>(84 app: Hono<E, S, BasePath>85) => {86 return awslambda.streamifyResponse(87 async (88 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,89 responseStream: NodeJS.WritableStream,90 context: LambdaContext91 ) => {92 try {93 const req = createRequest(event)94 const requestContext = getRequestContext(event)9596 const res = await app.fetch(req, {97 requestContext,98 context,99 })100101 // Check content type102 const httpResponseMetadata = {103 statusCode: res.status,104 headers: Object.fromEntries(res.headers.entries()),105 }106107 if (res.body) {108 await streamToNodeStream(109 res.body.getReader(),110 awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)111 )112 }113 } catch (error) {114 console.error('Error processing request:', error)115 responseStream.write('Internal Server Error')116 } finally {117 responseStream.end()118 }119 }120 )

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)watanybefore adoptioneefdb27

lines 121–122why, one step back
121}
122

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 123–125why, one step back
123/**
124 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)125 */

fix(types): remove type-errors for routes (#1371)Yusuke Wadabefore adoption6034dd7

line 126why, one step back
126export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(

fix(adapter/aws-lambda): use content-encoding to determine isBase64Encoded (#1295)byunghoo.yubefore adoptiona7dd281

lines 127–128why, one step back
127 app: Hono<E, S, BasePath>
128) => {

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

line 129why, one step back
129 return async (

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

lines 130–131why, one step back
130 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,
131 lambdaContext?: LambdaContext

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 132–133why, one step back
132 ): Promise<APIGatewayProxyResult> => {
133 const req = createRequest(event)

fix(adaptor): Access to custom request context on AWS Lambda Adaptor (#1305)watanybefore adoptioneefdb27

lines 134–135why, one step back
134 const requestContext = getRequestContext(event)
135

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

lines 136–139why, one step back
136 const res = await app.fetch(req, {
137 requestContext,138 lambdaContext,139 })

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

line 140why, one step back
140

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

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 142–144why, one step back
142 }
143}144

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

lines 145–148why, one step back
145const createResult = async (
146 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,147 res: Response148): Promise<APIGatewayProxyResult> => {

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

line 149why, one step back
149 const contentType = res.headers.get('content-type')

fix(adapter/aws-lambda): use content-encoding to determine isBase64Encoded (#1295)byunghoo.yubefore adoptiona7dd281

line 150why, one step back
150 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

line 151why, one step back
151

fix(adapter/aws-lambda): use content-encoding to determine isBase64Encoded (#1295)byunghoo.yubefore adoptiona7dd281

lines 152–156why, one step back
152 if (!isBase64Encoded) {
153 const contentEncoding = res.headers.get('content-encoding')154 isBase64Encoded = isContentEncodingBinary(contentEncoding)155 }156

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 157–170why, one step back
157 let body: string
158 if (isBase64Encoded) {159 const buffer = await res.arrayBuffer()160 body = encodeBase64(buffer)161 } else {162 body = await res.text()163 }164 const result: APIGatewayProxyResult = {165 body: body,166 headers: {},167 statusCode: res.status,168 isBase64Encoded,169 }170

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

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 172–188why, one step back
172 res.headers.forEach((value, key) => {
173 result.headers[key] = value174 })175176 return result177}178179const createRequest = (180 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent181) => {182 const queryString = extractQueryString(event)183 const urlPath = `https://${event.requestContext.domainName}${184 isProxyEvent(event) ? event.path : event.rawPath185 }`186 const url = queryString ? `${urlPath}?${queryString}` : urlPath187188 const headers = new Headers()

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

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

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 190–200why, one step back
190 for (const [k, v] of Object.entries(event.headers)) {
191 if (v) headers.set(k, v)192 }193194 const method = 'httpMethod' in event ? event.httpMethod : event.requestContext.http.method195 const requestInit: RequestInit = {196 headers,197 method,198 }199200 if (event.body) {

fix: Safe modification of Buffer (#1238)watanybefore adoption301e142

line 201why, one step back
201 requestInit.body = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 202–217why, one step back
202 }
203204 return new Request(url, requestInit)205}206207const extractQueryString = (208 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent209) => {210 if (isProxyEvent(event)) {211 return Object.entries(event.queryStringParameters || {})212 .filter(([, value]) => value)213 .map(([key, value]) => `${key}=${value}`)214 .join('&')215 }216217 return isProxyEventV2(event) ? event.rawQueryString : event.rawQueryString

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

lines 218–246why, one step back
218}
219220const getCookies = (221 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,222 headers: Headers223) => {224 if (isProxyEventV2(event) && Array.isArray(event.cookies)) {225 headers.set('Cookie', event.cookies.join('; '))226 }227}228229const setCookies = (230 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,231 res: Response,232 result: APIGatewayProxyResult233) => {234 if (res.headers.has('set-cookie')) {235 const cookies = res.headers.get('set-cookie')?.split(', ')236 if (Array.isArray(cookies)) {237 if (isProxyEventV2(event)) {238 result.cookies = cookies239 } else {240 result.multiValueHeaders = {241 'set-cookie': cookies,242 }243 }244 res.headers.delete('set-cookie')245 }246 }

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

lines 247–264why, one step back
247}
248249const isProxyEvent = (250 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent251): event is APIGatewayProxyEvent => {252 return Object.prototype.hasOwnProperty.call(event, 'path')253}254255const isProxyEventV2 = (256 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent257): event is APIGatewayProxyEventV2 => {258 return Object.prototype.hasOwnProperty.call(event, 'rawPath')259}260261export const isContentTypeBinary = (contentType: string) => {262 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml)$/.test(263 contentType264 )

fix(adapter/aws-lambda): use content-encoding to determine isBase64Encoded (#1295)byunghoo.yubefore adoptiona7dd281

lines 265–271why, one step back
265}
266267export const isContentEncodingBinary = (contentEncoding: string | null) => {268 if (contentEncoding === null) {269 return false270 }271 return /^(gzip|deflate|compress|br)/.test(contentEncoding)

feat: add deleteCookie (#1190)ryoppippibefore adoptionbae5419

line 272why, one step back
272}