handler.ts
This file
Path
src/adapter/aws-lambda/handler.ts
269 lines · 7.3 KiB · TypeScript
Last changed by
refactor(lambda): aws lambda createResult method (#2038)Aris Kemperbefore adoption0800acc
History of this fileTake it
The walk stopped after 200 commits: lines older than 8ac21d3 point at it.
fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 1–6why, one step back1// @denoify-ignore2import 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 back7import type {8 ApiGatewayRequestContext,9 ApiGatewayRequestContextV2,10 ALBRequestContext,11} from './custom-context'feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0
line 12why, one step back12import type { LambdaContext } from './types'fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 13–17why, one step back1314// eslint-disable-next-line @typescript-eslint/ban-ts-comment15// @ts-ignore16globalThis.crypto ??= crypto17Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 18–20why, one step back18export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1920// When calling HTTP API or Lambda directly through function urlsMerge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a
line 21why, one step back21export interface APIGatewayProxyEventV2 {Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 22–23why, one step back22 version: string23 routeKey: stringfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
line 24why, one step back24 headers: Record<string, string | undefined>fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
line 25why, one step back25 cookies?: string[]fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 26–29why, one step back26 rawPath: string27 rawQueryString: string28 body: string | null29 isBase64Encoded: booleanMerge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 30–39why, one step back30 requestContext: ApiGatewayRequestContextV231 queryStringParameters?: {32 [name: string]: string | undefined33 }34 pathParameters?: {35 [name: string]: string | undefined36 }37 stageVariables?: {38 [name: string]: string | undefined39 }fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 40–41why, one step back40}41Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 42why, one step back42// When calling Lambda through an API GatewayMerge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a
line 43why, one step back43export interface APIGatewayProxyEvent {Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 44why, one step back44 version: stringfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 45–46why, one step back45 httpMethod: string46 headers: Record<string, string | undefined>fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 47–49why, one step back47 multiValueHeaders?: {48 [headerKey: string]: string[]49 }fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 50–54why, one step back50 path: string51 body: string | null52 isBase64Encoded: boolean53 queryStringParameters?: Record<string, string | undefined>54 requestContext: ApiGatewayRequestContextMerge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 55–60why, one step back55 resource: string56 multiValueQueryStringParameters?: {57 [parameterKey: string]: string[]58 }59 pathParameters?: Record<string, string>60 stageVariables?: Record<string, string>fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 61–62why, one step back61}62Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 63–65why, one step back63// When calling Lambda through an Application Load Balancer64export interface ALBProxyEvent {65 httpMethod: stringfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
line 66why, one step back66 headers: Record<string, string | undefined>Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 67why, one step back67 path: stringfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 68–69why, one step back68 body: string | null69 isBase64Encoded: booleanMerge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 70–71why, one step back70 queryStringParameters?: Record<string, string | undefined>71 requestContext: ALBRequestContextfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 72–73why, one step back72}73fix(aws-lambda): export `APIGatewayProxyResult` (#1711)juhobefore adoption0a2b54a
line 74why, one step back74export interface APIGatewayProxyResult {fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
line 75why, one step back75 statusCode: numberMerge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 76why, one step back76 statusDescription?: stringfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 77–78why, one step back77 body: string78 headers: Record<string, string>fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 79–82why, one step back79 cookies?: string[]80 multiValueHeaders?: {81 [headerKey: string]: string[]82 }fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 83–86why, one step back83 isBase64Encoded: boolean84}8586const getRequestContext = (Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 87–88why, one step back87 event: LambdaEvent88): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
line 89why, one step back89 return event.requestContextMerge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a
lines 90–111why, one step back90}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 back112 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a
lines 113–117why, one step back113 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 back118 event,Merge pull request #1690 from honojs/nextYusuke Wadabefore adoption5e3e85a
lines 119–142why, one step back119 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 )fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 143–151why, one step back143}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 back152 event: LambdaEvent,feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0
line 153why, one step back153 lambdaContext?: LambdaContextfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 154–157why, one step back154 ): Promise<APIGatewayProxyResult> => {155 const req = createRequest(event)156 const requestContext = getRequestContext(event)157feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0
line 158why, one step back158 const res = await app.fetch(req, {Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 159why, one step back159 event,feat(adaptor): Accessable Lambda "Context" (#1523)watanybefore adoption43749a0
lines 160–162why, one step back160 requestContext,161 lambdaContext,162 })fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
line 163why, one step back163fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
line 164why, one step back164 return createResult(event, res)fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 165–167why, one step back165 }166}167Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 168why, one step back168const createResult = async (event: LambdaEvent, res: Response): Promise<APIGatewayProxyResult> => {fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 169–176why, one step back169 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 }176refactor(lambda): aws lambda createResult method (#2038)Aris Kemperbefore adoption0800acc
lines 177–178why, one step back177 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()178fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 179–185why, one step back179 const result: APIGatewayProxyResult = {180 body: body,181 headers: {},182 statusCode: res.status,183 isBase64Encoded,184 }185fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
line 186why, one step back186 setCookies(event, res, result)fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 187–193why, one step back187 res.headers.forEach((value, key) => {188 result.headers[key] = value189 })190191 return result192}193Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 194why, one step back194const createRequest = (event: LambdaEvent) => {fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
line 195why, one step back195 const queryString = extractQueryString(event)Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 196–201why, one step back196 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}`fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 202–204why, one step back202 const url = queryString ? `${urlPath}?${queryString}` : urlPath203204 const headers = new Headers()fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
line 205why, one step back205 getCookies(event, headers)fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 206–209why, one step back206 for (const [k, v] of Object.entries(event.headers)) {207 if (v) headers.set(k, v)208 }209Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 210why, one step back210 const method = isProxyEventV2(event) ? event.requestContext.http.method : event.httpMethodfix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 211–222why, one step back211 const requestInit: RequestInit = {212 headers,213 method,214 }215216 if (event.body) {217 requestInit.body = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body218 }219220 return new Request(url, requestInit)221}222Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 223–229why, one step back223const extractQueryString = (event: LambdaEvent) => {224 return isProxyEventV2(event)225 ? event.rawQueryString226 : Object.entries(event.queryStringParameters || {})227 .filter(([, value]) => value)228 .map(([key, value]) => `${key}=${value}`)229 .join('&')fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 230–231why, one step back230}231Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 232why, one step back232const getCookies = (event: LambdaEvent, headers: Headers) => {fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 233–237why, one step back233 if (isProxyEventV2(event) && Array.isArray(event.cookies)) {234 headers.set('Cookie', event.cookies.join('; '))235 }236}237Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 238why, one step back238const setCookies = (event: LambdaEvent, res: Response, result: APIGatewayProxyResult) => {fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 239–251why, one step back239 if (res.headers.has('set-cookie')) {240 const cookies = res.headers.get('set-cookie')?.split(', ')241 if (Array.isArray(cookies)) {242 if (isProxyEventV2(event)) {243 result.cookies = cookies244 } else {245 result.multiValueHeaders = {246 'set-cookie': cookies,247 }248 }249 res.headers.delete('set-cookie')250 }251 }fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 252–253why, one step back252}253Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 254why, one step back254const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 255–258why, one step back255 return Object.prototype.hasOwnProperty.call(event, 'rawPath')256}257258export const isContentTypeBinary = (contentType: string) => {fix: add missing tail to svg regex (#1788)Elias Brangebefore adoption521db64
line 259why, one step back259 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(fix(context): different types using `jsonT()` (#1379)Yusuke Wadabefore adoption8ac21d3
lines 260–269why, one step back260 contentType261 )262}263264export const isContentEncodingBinary = (contentEncoding: string | null) => {265 if (contentEncoding === null) {266 return false267 }268 return /^(gzip|deflate|compress|br)/.test(contentEncoding)269}