8

目前,我使用以下内容为 RestApi 键入 lambda 函数:

import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {}

这不适用于新的 AWS Gateway HTTP API,其中 HTTP 方法可以使用event.requestContext.http.method.

我应该使用其他类型吗?

4

2 回答 2

3

我应该使用其他类型吗?

我不这么认为。这些类型可通过DefinitelyTyped 获得。[1] 查看有关“aws-lambda”类型的一些问题,您会注意到 API Gateway 类型不经常更新。[2]

此外,API Gateway 的有效负载格式版本已更改,请参阅 [3]:

有效负载格式版本指定 API Gateway 发送到 Lambda 集成的数据格式,以及 API Gateway 如何解释来自 Lambda 的响应。如果您未指定有效负载格式版本,AWS 管理控制台默认使用最新版本。如果您使用 AWS CLI、AWS CloudFormation 或开发工具包创建 Lambda 集成,则必须指定 payloadFormatVersion。支持的值为 1.0 和 2.0。

我猜您使用的是最新版本2.0。2.0 版提供 HTTP 方法作为属性requestContext.http.method

1.0 版将 HTTP 方法作为属性requestContext.httpMethod提供。

解决方案

您可以 1.) 为新的有效负载格式版本编写类型,并通过 PR 将它们提交给包“@types/aws-lambda”或 2.) 将您的 API 网关设置为使用版本 1.0。

老实说,我不知道 HTTP API 是否可以使用有效负载版本 1.0。也许 AWS 正在对新 API 执行最新版本,因为不需要支持旧格式。

参考

[1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/aws-lambda/trigger/api-gateway-proxy.d.ts
[2] https://github.com/DefinitelyTyped/DefinitelyTyped /issues/38720#issuecomment-586051966
[3] https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html

于 2020-05-29T15:17:45.010 回答
2

接受的答案已过时。aws-lambda现在也出口APIGatewayProxyEventV2

import { APIGatewayProxyEventV2 } from 'aws-lambda'
于 2021-11-09T12:20:01.680 回答