Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

558 lines 路 16.8 KiB 路 TypeScript

Last changed by

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

History of this file

Take it

1import type { Hono } from '../../hono'2import type { Env, Schema } from '../../types'3import { decodeBase64, encodeBase64 } from '../../utils/encode'4import type {5  ALBRequestContext,6  ApiGatewayRequestContext,7  ApiGatewayRequestContextV2,8  Handler,9  LambdaContext,10} from './types'1112export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1314// When calling HTTP API or Lambda directly through function urls15export interface APIGatewayProxyEventV2 {16  version: string17  routeKey: string18  headers: Record<string, string | undefined>19  multiValueHeaders?: undefined20  cookies?: string[]21  rawPath: string22  rawQueryString: string23  body: string | null24  isBase64Encoded: boolean25  requestContext: ApiGatewayRequestContextV226  queryStringParameters?: {27    [name: string]: string | undefined28  }29  pathParameters?: {30    [name: string]: string | undefined31  }32  stageVariables?: {33    [name: string]: string | undefined34  }35}3637// When calling Lambda through an API Gateway38export interface APIGatewayProxyEvent {39  version: string40  httpMethod: string41  headers: Record<string, string | undefined>42  multiValueHeaders?: {43    [headerKey: string]: string[]44  }45  path: string46  body: string | null47  isBase64Encoded: boolean48  queryStringParameters?: Record<string, string | undefined>49  requestContext: ApiGatewayRequestContext50  resource: string51  multiValueQueryStringParameters?: {52    [parameterKey: string]: string[]53  }54  pathParameters?: Record<string, string>55  stageVariables?: Record<string, string>56}5758// When calling Lambda through an Application Load Balancer59export interface ALBProxyEvent {60  httpMethod: string61  headers?: Record<string, string | undefined>62  multiValueHeaders?: Record<string, string[] | undefined>63  path: string64  body: string | null65  isBase64Encoded: boolean66  queryStringParameters?: Record<string, string | undefined>67  multiValueQueryStringParameters?: {68    [parameterKey: string]: string[]69  }70  requestContext: ALBRequestContext71}7273type WithHeaders = {74  headers: Record<string, string>75  multiValueHeaders?: undefined76}77type WithMultiValueHeaders = {78  headers?: undefined79  multiValueHeaders: Record<string, string[]>80}8182export type APIGatewayProxyResult = {83  statusCode: number84  statusDescription?: string85  body: string86  cookies?: string[]87  isBase64Encoded: boolean88} & (WithHeaders | WithMultiValueHeaders)8990const getRequestContext = (91  event: LambdaEvent92): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {93  return event.requestContext94}9596const streamToNodeStream = async (97  reader: ReadableStreamDefaultReader<Uint8Array>,98  writer: NodeJS.WritableStream99): Promise<void> => {100  let readResult = await reader.read()101  while (!readResult.done) {102    writer.write(readResult.value)103    readResult = await reader.read()104  }105  writer.end()106}107108export const streamHandle = <109  E extends Env = Env,110  S extends Schema = {},111  BasePath extends string = '/'112>(113  app: Hono<E, S, BasePath>114): Handler => {115  // @ts-expect-error awslambda is not a standard API116  return awslambda.streamifyResponse(117    async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {118      const processor = getProcessor(event)119      try {120        const req = processor.createRequest(event)121        const requestContext = getRequestContext(event)122123        const res = await app.fetch(req, {124          event,125          requestContext,126          context,127        })128129        const headers: Record<string, string> = {}130        const cookies: string[] = []131        res.headers.forEach((value, name) => {132          if (name === 'set-cookie') {133            cookies.push(value)134          } else {135            headers[name] = value136          }137        })138139        // Check content type140        const httpResponseMetadata = {141          statusCode: res.status,142          headers,143          cookies,144        }145146        // Update response stream147        // @ts-expect-error awslambda is not a standard API148        responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)149150        if (res.body) {151          await streamToNodeStream(res.body.getReader(), responseStream)152        } else {153          responseStream.write('')154        }155      } catch (error) {156        console.error('Error processing request:', error)157        responseStream.write('Internal Server Error')158      } finally {159        responseStream.end()160      }161    }162  )163}164165type HandleOptions = {166  isContentTypeBinary: ((contentType: string) => boolean) | undefined167}168169/**170 * Converts a Hono application to an AWS Lambda handler.171 *172 * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),173 * and Lambda Function URLs.174 *175 * @param app - The Hono application instance176 * @param options - Optional configuration177 * @param options.isContentTypeBinary - A function to determine if the content type is binary.178 *                                      If not provided, the default function will be used.179 * @returns Lambda handler function180 *181 * @example182 * ```js183 * import { Hono } from 'hono'184 * import { handle } from 'hono/aws-lambda'185 *186 * const app = new Hono()187 *188 * app.get('/', (c) => c.text('Hello from Lambda'))189 * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))190 *191 * export const handler = handle(app)192 * ```193 *194 * @example195 * ```js196 * // With custom binary content type detection197 * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda'198 * export const handler = handle(app, {199 *   isContentTypeBinary: (contentType) => {200 *     if (defaultIsContentTypeBinary(contentType)) {201 *       // default logic same as prior to v4.8.4202 *       return true203 *     }204 *     return contentType.startsWith('image/') || contentType === 'application/pdf'205 *   }206 * })207 * ```208 */209export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(210  app: Hono<E, S, BasePath>,211  { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }212): (<L extends LambdaEvent>(213  event: L,214  lambdaContext?: LambdaContext215) => Promise<216  APIGatewayProxyResult &217    (L extends { multiValueHeaders: Record<string, string[]> }218      ? WithMultiValueHeaders219      : WithHeaders)220>) => {221  // @ts-expect-error FIXME: Fix return typing222  return async (event, lambdaContext?) => {223    const processor = getProcessor(event)224225    const req = processor.createRequest(event)226    const requestContext = getRequestContext(event)227228    const res = await app.fetch(req, {229      event,230      requestContext,231      lambdaContext,232    })233234    return processor.createResult(event, res, { isContentTypeBinary })235  }236}237238export abstract class EventProcessor<E extends LambdaEvent> {239  protected abstract getPath(event: E): string240241  protected abstract getMethod(event: E): string242243  protected abstract getQueryString(event: E): string244245  protected abstract getHeaders(event: E): Headers246247  protected abstract getCookies(event: E, headers: Headers): void248249  protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void250251  createRequest(event: E): Request {252    const queryString = this.getQueryString(event)253    const domainName =254      event.requestContext && 'domainName' in event.requestContext255        ? event.requestContext.domainName256        : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]257    const path = this.getPath(event)258    const urlPath = `https://${domainName}${path}`259    const url = queryString ? `${urlPath}?${queryString}` : urlPath260261    const headers = this.getHeaders(event)262263    const method = this.getMethod(event)264    const requestInit: RequestInit = {265      headers,266      method,267    }268269    if (event.body) {270      requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body271    }272273    return new Request(url, requestInit)274  }275276  async createResult(277    event: E,278    res: Response,279    options: Pick<HandleOptions, 'isContentTypeBinary'>280  ): Promise<APIGatewayProxyResult> {281    // determine whether the response body should be base64 encoded282    const contentType = res.headers.get('content-type')283    const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided284    let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false285286    if (!isBase64Encoded) {287      const contentEncoding = res.headers.get('content-encoding')288      isBase64Encoded = isContentEncodingBinary(contentEncoding)289    }290291    const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()292293    const result: APIGatewayProxyResult = {294      body: body,295      statusCode: res.status,296      isBase64Encoded,297      ...(event.multiValueHeaders298        ? {299            multiValueHeaders: {},300          }301        : {302            headers: {},303          }),304    }305306    this.setCookies(event, res, result)307    if (result.multiValueHeaders) {308      res.headers.forEach((value, key) => {309        result.multiValueHeaders[key] = [value]310      })311    } else {312      res.headers.forEach((value, key) => {313        result.headers[key] = value314      })315    }316317    return result318  }319320  setCookies(event: E, res: Response, result: APIGatewayProxyResult) {321    if (res.headers.has('set-cookie')) {322      const cookies = res.headers.getSetCookie323        ? res.headers.getSetCookie()324        : Array.from(res.headers.entries())325            .filter(([k]) => k === 'set-cookie')326            .map(([, v]) => v)327328      if (Array.isArray(cookies)) {329        this.setCookiesToResult(result, cookies)330        res.headers.delete('set-cookie')331      }332    }333  }334}335336export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {337  protected getPath(event: APIGatewayProxyEventV2): string {338    return event.rawPath339  }340341  protected getMethod(event: APIGatewayProxyEventV2): string {342    return event.requestContext.http.method343  }344345  protected getQueryString(event: APIGatewayProxyEventV2): string {346    return event.rawQueryString347  }348349  protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {350    if (Array.isArray(event.cookies)) {351      headers.set('Cookie', event.cookies.join('; '))352    }353  }354355  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {356    result.cookies = cookies357  }358359  protected getHeaders(event: APIGatewayProxyEventV2): Headers {360    const headers = new Headers()361    this.getCookies(event, headers)362    if (event.headers) {363      for (const [k, v] of Object.entries(event.headers)) {364        if (v) {365          headers.set(k, v)366        }367      }368    }369    return headers370  }371}372373const v2Processor: EventV2Processor = new EventV2Processor()374375export class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {376  protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {377    return event.path378  }379380  protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {381    return event.httpMethod382  }383384  protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {385    // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both386    if (event.multiValueQueryStringParameters) {387      return Object.entries(event.multiValueQueryStringParameters || {})388        .filter(([, value]) => value)389        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)390        .join('&')391    } else {392      return Object.entries(event.queryStringParameters || {})393        .filter(([, value]) => value)394        .map(([key, value]) => `${key}=${value}`)395        .join('&')396    }397  }398399  protected getCookies(400    // eslint-disable-next-line @typescript-eslint/no-unused-vars401    event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,402    // eslint-disable-next-line @typescript-eslint/no-unused-vars403    headers: Headers404  ): void {405    // nop406  }407408  protected getHeaders(event: APIGatewayProxyEvent): Headers {409    const headers = new Headers()410    this.getCookies(event, headers)411    if (event.headers) {412      for (const [k, v] of Object.entries(event.headers)) {413        if (v) {414          headers.set(k, v)415        }416      }417    }418    if (event.multiValueHeaders) {419      for (const [k, values] of Object.entries(event.multiValueHeaders)) {420        if (values) {421          // avoid duplicating already set headers422          const foundK = headers.get(k)423          values.forEach((v) => (!foundK || !foundK.includes(v)) && headers.append(k, v))424        }425      }426    }427    return headers428  }429430  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {431    result.multiValueHeaders = {432      'set-cookie': cookies,433    }434  }435}436437const v1Processor: EventV1Processor = new EventV1Processor()438439export class ALBProcessor extends EventProcessor<ALBProxyEvent> {440  protected getHeaders(event: ALBProxyEvent): Headers {441    const headers = new Headers()442    // if multiValueHeaders is present the ALB will use it instead of the headers field443    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers444    if (event.multiValueHeaders) {445      for (const [key, values] of Object.entries(event.multiValueHeaders)) {446        if (values && Array.isArray(values)) {447          // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f448          headers.set(key, values.join('; '))449        }450      }451    } else {452      for (const [key, value] of Object.entries(event.headers ?? {})) {453        if (value) {454          headers.set(key, value)455        }456      }457    }458    return headers459  }460461  protected getPath(event: ALBProxyEvent): string {462    return event.path463  }464465  protected getMethod(event: ALBProxyEvent): string {466    return event.httpMethod467  }468469  protected getQueryString(event: ALBProxyEvent): string {470    // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both471    /*472      In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:473      Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency474      {475        ...476        queryStringParameters: { select: 'currency' },477        multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },478      }479      The expected results is for select to be an array with two items. However the pre-fix code is only returning one item ('currency') in the array.480      A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.481    */482    if (event.multiValueQueryStringParameters) {483      return Object.entries(event.multiValueQueryStringParameters || {})484        .filter(([, value]) => value)485        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)486        .join('&')487    } else {488      return Object.entries(event.queryStringParameters || {})489        .filter(([, value]) => value)490        .map(([key, value]) => `${key}=${value}`)491        .join('&')492    }493  }494495  protected getCookies(event: ALBProxyEvent, headers: Headers): void {496    let cookie497    if (event.multiValueHeaders) {498      cookie = event.multiValueHeaders['cookie']?.join('; ')499    } else {500      cookie = event.headers ? event.headers['cookie'] : undefined501    }502    if (cookie) {503      headers.append('Cookie', cookie)504    }505  }506507  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {508    // when multi value headers is enabled509    if (result.multiValueHeaders) {510      result.multiValueHeaders['set-cookie'] = cookies511    } else {512      // otherwise serialize the set-cookie513      result.headers['set-cookie'] = cookies.join(', ')514    }515  }516}517518const albProcessor: ALBProcessor = new ALBProcessor()519520export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {521  if (isProxyEventALB(event)) {522    return albProcessor523  }524  if (isProxyEventV2(event)) {525    return v2Processor526  }527  return v1Processor528}529530const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {531  if (event.requestContext) {532    return Object.hasOwn(event.requestContext, 'elb')533  }534  return false535}536537const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {538  return Object.hasOwn(event, 'rawPath')539}540541/**542 * Check if the given content type is binary.543 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().544 * @param contentType The content type to check.545 * @returns True if the content type is binary, false otherwise.546 */547export const defaultIsContentTypeBinary = (contentType: string): boolean => {548  return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(549    contentType550  )551}552553export const isContentEncodingBinary = (contentEncoding: string | null) => {554  if (contentEncoding === null) {555    return false556  }557  return /^(gzip|deflate|compress|br)/.test(contentEncoding)558}