handler.ts
This file
Path
src/adapter/aws-lambda/handler.ts
274 lines · 7.4 KiB · TypeScript
Last changed by
fix: add missing tail to svg regex (#1788)Elias Brangebefore adoption521db64
History of this fileTake it
The walk stopped after 200 commits: lines older than e070191 point at it.
feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 1–3why, one step back1// @denoify-ignore2import crypto from 'crypto'3import type { Hono } from '../../hono'fix(types): remove type-errors for routes (#1371)Yusuke Wadabefore adoption6034dd7
line 4why, one step back4import type { Env, Schema } from '../../types'feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 5–6why, one step back56import { 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'feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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: stringfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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[]feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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 }feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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: stringfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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 }feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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>feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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: stringfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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: stringfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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: ALBRequestContextfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 72–73why, one step back72}73fix(aws-lambda): export `APIGatewayProxyResult` (#1711)juhobefore adoption0a2b54a
line 74why, one step back74export interface APIGatewayProxyResult {feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
line 75why, one step back75 statusCode: numberMerge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 76why, one step back76 statusDescription?: stringfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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 }feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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 => {feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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 )feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 143–147why, one step back143}144145/**146 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)147 */fix(types): remove type-errors for routes (#1371)Yusuke Wadabefore adoption6034dd7
line 148why, one step back148export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 149–151why, one step back149 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?: LambdaContextfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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 })feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
line 163why, one step back163fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
line 164why, one step back164 return createResult(event, res)feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
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> => {feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 169–190why, 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 }176177 let body: string178 if (isBase64Encoded) {179 const buffer = await res.arrayBuffer()180 body = encodeBase64(buffer)181 } else {182 body = await res.text()183 }184 const result: APIGatewayProxyResult = {185 body: body,186 headers: {},187 statusCode: res.status,188 isBase64Encoded,189 }190fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
line 191why, one step back191 setCookies(event, res, result)feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 192–198why, one step back192 res.headers.forEach((value, key) => {193 result.headers[key] = value194 })195196 return result197}198Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 199why, one step back199const createRequest = (event: LambdaEvent) => {feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
line 200why, one step back200 const queryString = extractQueryString(event)Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 201–206why, one step back201 const domainName =202 event.requestContext && 'domainName' in event.requestContext203 ? event.requestContext.domainName204 : event.headers['host']205 const path = isProxyEventV2(event) ? event.rawPath : event.path206 const urlPath = `https://${domainName}${path}`feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 207–209why, one step back207 const url = queryString ? `${urlPath}?${queryString}` : urlPath208209 const headers = new Headers()fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
line 210why, one step back210 getCookies(event, headers)feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 211–214why, one step back211 for (const [k, v] of Object.entries(event.headers)) {212 if (v) headers.set(k, v)213 }214Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 215why, one step back215 const method = isProxyEventV2(event) ? event.requestContext.http.method : event.httpMethodfeat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 216–227why, one step back216 const requestInit: RequestInit = {217 headers,218 method,219 }220221 if (event.body) {222 requestInit.body = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body223 }224225 return new Request(url, requestInit)226}227Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 228–234why, one step back228const extractQueryString = (event: LambdaEvent) => {229 return isProxyEventV2(event)230 ? event.rawQueryString231 : Object.entries(event.queryStringParameters || {})232 .filter(([, value]) => value)233 .map(([key, value]) => `${key}=${value}`)234 .join('&')fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 235–236why, one step back235}236Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 237why, one step back237const getCookies = (event: LambdaEvent, headers: Headers) => {fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 238–242why, one step back238 if (isProxyEventV2(event) && Array.isArray(event.cookies)) {239 headers.set('Cookie', event.cookies.join('; '))240 }241}242Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 243why, one step back243const setCookies = (event: LambdaEvent, res: Response, result: APIGatewayProxyResult) => {fix(lambda): Aws lambda cookies fix (#1613)Ochirjav Jargalsaikhanbefore adoption5f02375
lines 244–256why, one step back244 if (res.headers.has('set-cookie')) {245 const cookies = res.headers.get('set-cookie')?.split(', ')246 if (Array.isArray(cookies)) {247 if (isProxyEventV2(event)) {248 result.cookies = cookies249 } else {250 result.multiValueHeaders = {251 'set-cookie': cookies,252 }253 }254 res.headers.delete('set-cookie')255 }256 }feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 257–258why, one step back257}258Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 259why, one step back259const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 260–263why, one step back260 return Object.prototype.hasOwnProperty.call(event, 'rawPath')261}262263export const isContentTypeBinary = (contentType: string) => {fix: add missing tail to svg regex (#1788)Elias Brangebefore adoption521db64
line 264why, one step back264 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191
lines 265–274why, one step back265 contentType266 )267}268269export const isContentEncodingBinary = (contentEncoding: string | null) => {270 if (contentEncoding === null) {271 return false272 }273 return /^(gzip|deflate|compress|br)/.test(contentEncoding)274}