aws lambda_AWS Lambdas的打字稿第一个中间件

aws lambda

Over the last years, TypeScript has become more and more prevalent in the NodeJS backend world. This also applies for AWS lambdas, especially since AWS is also pushing TypeScript with AWS CDK.

在过去的几年中,TypeScript在NodeJS后端世界中越来越流行。 这也适用于AWS lambda,尤其是因为AWS还通过AWS CDK推送TypeScript。

For AWS lambda middleware, there is a strongly-typed alternative now: lambda-middleware. It allows you to wrap your handler with middleware and get TypeScript to tell you about how the middleware changes your event and response objects.

对于AWS Lambda中间件,现在有一个强类型的替代品: lambda-middleware 。 它允许您使用中间件包装处理程序,并获取TypeScript来告诉您有关中间件如何更改事件和响应对象的信息。

一个简单的例子 (A simple example)

Let’s say you have the following lambda function:

假设您具有以下lambda函数:

import { APIGatewayProxyResult, APIGatewayEvent, Context } from "aws-lambda";
export async function add(event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> {
const { a, b } = JSON.parse(event.body ?? "{}");
const sum = a + b;
return {
statusCode: 200,
body: JSON.stringify({ result: sum })
}
}

This code isn’t really typesafe yet: JSON.parse will return any, but there is no guarantee that a and b are actually set. It is also a mix between the actual business logic and code that transforms from and to http requests.

这段代码还不是真正的类型安全:JSON.parse将返回任何值,但是不能保证a和b被实际设置。 它也是实际业务逻辑和从HTTP请求转换为HTTP请求的代码之间的混合。

What does the code look like with lambda-middleware?

lambda中间件的代码是什么样的?

import { APIGatewayProxyResult, APIGatewayEvent, Context } from "aws-lambda";
import { IsNumber } from "class-validator";
import { compose } from "@lambda-middleware/compose";
import { classValidator } from "@lambda-middleware/class-validator";
import { errorHandler } from "@lambda-middleware/http-error-handler";
import { jsonSerializer } from "@lambda-middleware/json-serializer";
class Summands {
@IsNumber()
a!: number;
@IsNumber()
b!: number;
}
async function sum({
body: { a, b },
}: {
body: Summands;
}): Promise<{ result: number }> {
return { result: a + b };
}
export const add: (
event: APIGatewayEvent,
context: Context
) => Promise<APIGatewayProxyResult> = compose(
errorHandler(),
jsonSerializer(),
classValidator({ bodyType: Summands })
)(sum);

The actual business logic is now extracted into a function called “sum” that doesn’t really know anything about http requests. The classValidator and jsonSerializer middlewares take care of converting from and to http requests, while validating the input at the same time.

现在,实际的业务逻辑被提取到一个名为“ sum”的函数中,该函数对http请求一无所知。 classValidator和jsonSerializer中间件负责在请求和请求之间进行转换,同时验证输入。

Where does the strict typing come in? Let’s see the error messages we get if we introduce some otherwise easy-to-miss bugs.

严格输入从何而来? 让我们看看如果引入了一些其他容易遗漏的错误,则会得到错误消息。

If we remove jsonSerializer() from the list of middlewares, we get the following error:

如果从中间件列表中删除jsonSerializer(),则会出现以下错误:

Error:(31, 3) TS2345: Argument of type '({ body: { a, b }, }: { body: Summands; }) => Promise<{ result: number; }>' is not assignable to parameter of type 'PromiseHandler<WithBody<APIGatewayProxyEvent, Summands>, APIGatewayProxyResult>'.
Type 'Promise<{ result: number; }>' is not assignable to type 'Promise<APIGatewayProxyResult>'.
Type '{ result: number; }' is missing the following properties from type 'APIGatewayProxyResult': statusCode, body

TypeScript warns us that we never converted our business-logic result to an APIGatewaryProxyResult.

TypeScript警告我们不要将业务逻辑结果转换为APIGatewaryProxyResult。

Let’s now change our handler:

现在让我们更改处理程序:

async function sum({
body: { a, b, c},
}: {
body: { a: number, b: number, c: number };
}): Promise<{ result: number }> {
return { result: a + b + c};
}

This gives us the following error message:

这给我们以下错误信息:

Error:(31, 3) TS2345: Argument of type '({ body: { a, b, c }, }: { body: { a: number; b: number; c: number; }; }) => Promise<{ result: number; }>' is not assignable to parameter of type 'PromiseHandler<WithBody<APIGatewayProxyEvent, Summands>, APIGatewayProxyResult>'.
Types of parameters '__0' and 'event' are incompatible.
Type 'WithBody<APIGatewayProxyEvent, Summands>' is not assignable to type '{ body: { a: number; b: number; c: number; }; }'.
Types of property 'body' are incompatible.
Property 'c' is missing in type 'Summands' but required in type '{ a: number; b: number; c: number; }'.

TypeScript saved us from using a property “c” that we never validated is on the request.

TypeScript使用了我们从未在请求​​中验证的属性“ c”,从而避免了我们的使用。

下一步 (Next steps)

If you want to read more about the lambda middleware itself, best have a look at its documentation. There’s also an article about different ways to set up middleware for lambdas and their pros and cons

如果您想了解有关lambda中间件本身的更多信息,最好查看其文档 。 还有一篇文章介绍了为lambda设置中间件的不同方法及其优缺点

翻译自: https://medium.com/@daniel.bartholomae/typescript-first-middleware-for-aws-lambdas-25e4f3abf01d

aws lambda

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值