跳转到内容

tRPC

tRPC 是一个用于在 TypeScript 中构建端到端类型安全 API 的框架。使用 tRPC 时,API 操作输入和输出的变更会立即反映在客户端代码中,并可在 IDE 中直接查看,无需重新构建项目。

tRPC API 生成器会创建一个新的 tRPC API,并配置 AWS CDK 基础设施。生成的后端使用 AWS Lambda 进行无服务器部署,并通过 Zod 实现模式验证。它集成了 AWS Lambda Powertools 用于可观测性,包括日志记录、AWS X-Ray 追踪和 CloudWatch 指标。

您可以通过两种方式生成新的 tRPC API:

  1. 安装 Nx Console VSCode Plugin 如果您尚未安装
  2. 在VSCode中打开Nx控制台
  3. 点击 Generate (UI) 在"Common Nx Commands"部分
  4. 搜索 @aws/nx-plugin - ts#trpc-api
  5. 填写必需参数
    • 点击 Generate
    参数 类型 默认值 描述
    name 必需 string - The name of the API (required). Used to generate class names and file paths.
    computeType string ServerlessApiGatewayRestApi The type of compute to use to deploy this API. Choose between ServerlessApiGatewayRestApi (default) or ServerlessApiGatewayHttpApi.
    auth string IAM The method used to authenticate with your API. Choose between IAM (default), Cognito or None.
    directory string packages The directory to store the application in.

    生成器将在 <directory>/<api-name> 目录下创建以下项目结构:

    • 文件夹src
      • init.ts 后端 tRPC 初始化
      • router.ts tRPC 路由定义(Lambda 处理程序 API 入口点)
      • 文件夹schema 使用 Zod 的模式定义
        • echo.ts “echo” 过程输入输出的示例定义
      • 文件夹procedures 您的 API 暴露的过程(或操作)
        • echo.ts 示例过程
      • 文件夹middleware
        • error.ts 错误处理中间件
        • logger.ts 配置 AWS Powertools 用于 Lambda 日志记录的中间件
        • tracer.ts 配置 AWS Powertools 用于 Lambda 追踪的中间件
        • metrics.ts 配置 AWS Powertools 用于 Lambda 指标的中间件
      • local-server.ts 本地开发服务器的 tRPC 独立适配器入口点
      • 文件夹client
        • index.ts 用于机器间 API 调用的类型安全客户端
    • tsconfig.json TypeScript 配置
    • project.json 项目配置和构建目标

    生成器还会在 packages/common/constructs 目录下创建用于部署 API 的 CDK 构造。

    从高层次来看,tRPC API 由将请求分派到特定过程的路由器组成。每个过程都有通过 Zod 模式定义的输入和输出。

    src/schema 目录包含客户端和服务器代码共享的类型。在此包中,这些类型使用 Zod(一个 TypeScript 优先的模式声明和验证库)定义。

    示例模式可能如下所示:

    import { z } from 'zod';
    // 模式定义
    export const UserSchema = z.object({
    name: z.string(),
    height: z.number(),
    dateOfBirth: z.string().datetime(),
    });
    // 对应的 TypeScript 类型
    export type User = z.TypeOf<typeof UserSchema>;

    根据上述模式,User 类型等效于以下 TypeScript:

    interface User {
    name: string;
    height: number;
    dateOfBirth: string;
    }

    模式由服务器和客户端代码共享,在更改 API 使用的结构时提供单一更新点。

    您的 tRPC API 在运行时自动验证模式,无需在后端手动编写验证逻辑。

    Zod 提供了强大的工具来组合或派生模式,如 .merge.pick.omit 等。更多信息请参阅 Zod 文档网站

    您可以在 src/router.ts 中找到 API 的入口点。该文件包含 Lambda 处理程序,根据调用的操作将请求路由到“过程”。每个过程定义预期的输入、输出和实现。

    生成的示例路由器有一个名为 echo 的操作:

    import { echo } from './procedures/echo.js';
    export const appRouter = router({
    echo,
    });

    示例 echo 过程在 src/procedures/echo.ts 中生成:

    export const echo = publicProcedure
    .input(EchoInputSchema)
    .output(EchoOutputSchema)
    .query((opts) => ({ result: opts.input.message }));

    分解上述代码:

    • publicProcedure 定义 API 的公共方法,包括在 src/middleware 中设置的中间件。此中间件包含用于日志记录、追踪和指标的 AWS Lambda Powertools 集成。
    • input 接受定义操作预期输入的 Zod 模式。发送到此操作的请求会自动根据此模式验证。
    • output 接受定义操作预期输出的 Zod 模式。如果返回的输出不符合模式,您将在实现中看到类型错误。
    • query 接受定义 API 实现的函数。此实现接收 opts,其中包含传递给操作的 input,以及中间件设置的其他上下文(在 opts.ctx 中可用)。传递给 query 的函数必须返回符合 output 模式的输出。

    使用 query 定义实现表示该操作是非变更性的。使用此方法定义数据检索方法。要实现变更性操作,请改用 mutation 方法。

    如果添加新过程,请确保在 src/router.ts 中将其注册到路由器。

    在实现中,您可以通过抛出 TRPCError 向客户端返回错误响应。这些错误接受表示错误类型的 code,例如:

    throw new TRPCError({
    code: 'NOT_FOUND',
    message: '找不到请求的资源',
    });

    随着 API 的增长,您可能希望将相关操作分组。

    您可以使用嵌套路由器对操作进行分组,例如:

    import { getUser } from './procedures/users/get.js';
    import { listUsers } from './procedures/users/list.js';
    const appRouter = router({
    users: router({
    get: getUser,
    list: listUsers,
    }),
    ...
    })

    客户端随后会接收到此操作分组,例如在此情况下调用 listUsers 操作可能如下所示:

    client.users.list.query();

    AWS Lambda Powertools 日志记录器在 src/middleware/logger.ts 中配置,可通过 opts.ctx.logger 在 API 实现中访问。您可以使用此记录器将日志写入 CloudWatch Logs,并控制每个结构化日志消息中包含的额外值。例如:

    export const echo = publicProcedure
    .input(...)
    .output(...)
    .query(async (opts) => {
    opts.ctx.logger.info('操作调用输入', opts.input);
    return ...;
    });

    有关日志记录器的更多信息,请参阅 AWS Lambda Powertools 日志记录器文档

    AWS Lambda Powertools 指标在 src/middleware/metrics.ts 中配置,可通过 opts.ctx.metrics 在 API 实现中访问。您可以使用此功能在 CloudWatch 中记录指标,而无需导入和使用 AWS SDK,例如:

    export const echo = publicProcedure
    .input(...)
    .output(...)
    .query(async (opts) => {
    opts.ctx.metrics.addMetric('调用次数', 'Count', 1);
    return ...;
    });

    更多信息请参阅 AWS Lambda Powertools 指标文档

    AWS Lambda Powertools 追踪器在 src/middleware/tracer.ts 中配置,可通过 opts.ctx.tracer 在 API 实现中访问。您可以使用此功能添加 AWS X-Ray 追踪,以提供 API 请求性能和流程的详细洞察。例如:

    export const echo = publicProcedure
    .input(...)
    .output(...)
    .query(async (opts) => {
    const subSegment = opts.ctx.tracer.getSegment()!.addNewSubsegment('我的算法');
    // ... 要捕获的算法逻辑
    subSegment.close();
    return ...;
    });

    更多信息请参阅 AWS Lambda Powertools 追踪器文档

    您可以通过实现中间件向过程提供的上下文中添加额外值。

    例如,让我们在 src/middleware/identity.ts 中实现一些中间件,从 API 中提取调用用户的详细信息。

    此示例假设 auth 设置为 IAM。对于 Cognito 身份验证,身份中间件更直接,从 event 中提取相关声明。

    首先,我们定义要添加到上下文中的内容:

    export interface IIdentityContext {
    identity?: {
    sub: string;
    username: string;
    };
    }

    注意,我们向上下文定义了一个额外的_可选_属性。tRPC 会管理确保在正确配置此中间件的过程中有此定义。

    接下来,我们将实现中间件本身。其结构如下:

    export const createIdentityPlugin = () => {
    const t = initTRPC.context<...>().create();
    return t.procedure.use(async (opts) => {
    // 在此处添加过程前运行的逻辑
    const response = await opts.next(...);
    // 在此处添加过程后运行的逻辑
    return response;
    });
    };

    在我们的案例中,我们希望提取调用 Cognito 用户的详细信息。我们将通过从 API Gateway 事件中提取用户的主题 ID(或 “sub”)并从 Cognito 检索用户详细信息来实现。具体实现根据事件是由 REST API 还是 HTTP API 提供给我们的函数而略有不同:

    import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';
    import { initTRPC, TRPCError } from '@trpc/server';
    import { CreateAWSLambdaContextOptions } from '@trpc/server/adapters/aws-lambda';
    import { APIGatewayProxyEvent } from 'aws-lambda';
    export interface IIdentityContext {
    identity?: {
    sub: string;
    username: string;
    };
    }
    export const createIdentityPlugin = () => {
    const t = initTRPC.context<IIdentityContext & CreateAWSLambdaContextOptions<APIGatewayProxyEvent>>().create();
    const cognito = new CognitoIdentityProvider();
    return t.procedure.use(async (opts) => {
    const cognitoAuthenticationProvider = opts.ctx.event.requestContext?.identity?.cognitoAuthenticationProvider;
    let sub: string | undefined = undefined;
    if (cognitoAuthenticationProvider) {
    const providerParts = cognitoAuthenticationProvider.split(':');
    sub = providerParts[providerParts.length - 1];
    }
    if (!sub) {
    throw new TRPCError({
    code: 'FORBIDDEN',
    message: `无法确定调用用户`,
    });
    }
    const { Users } = await cognito.listUsers({
    // 假设用户池 ID 已在 Lambda 环境中配置
    UserPoolId: process.env.USER_POOL_ID!,
    Limit: 1,
    Filter: `sub="${sub}"`,
    });
    if (!Users || Users.length !== 1) {
    throw new TRPCError({
    code: 'FORBIDDEN',
    message: `未找到主题 ID 为 ${sub} 的用户`,
    });
    }
    // 向其他过程提供身份信息
    return await opts.next({
    ctx: {
    ...opts.ctx,
    identity: {
    sub,
    username: Users[0].Username!,
    },
    },
    });
    });
    };

    tRPC API 生成器在 common/constructs 文件夹中生成了用于部署 API 的 CDK 构造。您可以在 CDK 应用程序中使用此构造,例如:

    import { MyApi } from ':my-scope/common-constructs`;
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // 将 API 添加到堆栈
    const api = new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this).build(),
    });
    }
    }

    这将设置您的 API 基础设施,包括 AWS API Gateway REST 或 HTTP API、用于业务逻辑的 AWS Lambda 函数,以及基于所选 auth 方法的身份验证。

    REST/HTTP API CDK 构造被配置为为每个操作定义集成提供类型安全接口。

    您可以使用静态方法 defaultIntegrations 来应用默认模式,该模式会为每个操作定义单独的 AWS Lambda 函数:

    new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this).build(),
    });

    您可以通过 API 构造的 integrations 属性以类型安全的方式访问底层 AWS Lambda 函数。例如,如果您的 API 定义了名为 sayHello 的操作,并且需要为该函数添加权限,可以按如下方式操作:

    const api = new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this).build(),
    });
    // sayHello 的类型会对应 API 中定义的操作
    api.integrations.sayHello.handler.addToRolePolicy(new PolicyStatement({
    effect: Effect.ALLOW,
    actions: [...],
    resources: [...],
    }));

    如果要调整为每个默认集成创建 Lambda 函数时使用的选项,可以使用 withDefaultOptions 方法。例如,若希望所有 Lambda 函数都部署在 VPC 中:

    const vpc = new Vpc(this, 'Vpc', ...);
    new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this)
    .withDefaultOptions({
    vpc,
    })
    .build(),
    });

    您还可以通过 withOverrides 方法覆盖特定操作的集成。每个覆盖必须指定类型正确的 integration 属性(对应 HTTP 或 REST API 的 CDK 集成构造)。该方法同样具有类型安全性。例如,若要将 getDocumentation API 指向外部托管的文档网站:

    new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this)
    .withOverrides({
    getDocumentation: {
    integration: new HttpIntegration('https://example.com/documentation'),
    },
    })
    .build(),
    });

    此时通过 api.integrations.getDocumentation 访问时,该集成将不再包含 handler 属性。

    您还可以为集成添加其他类型化的属性。例如,如果为 REST API 创建了 S3 集成并需要后续引用特定操作的存储桶:

    const storageBucket = new Bucket(this, 'Bucket', { ... });
    const apiGatewayRole = new Role(this, 'ApiGatewayS3Role', {
    assumedBy: new ServicePrincipal('apigateway.amazonaws.com'),
    });
    storageBucket.grantRead(apiGatewayRole);
    const api = new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this)
    .withOverrides({
    getFile: {
    bucket: storageBucket,
    integration: new AwsIntegration({
    service: 's3',
    integrationHttpMethod: 'GET',
    path: `${storageBucket.bucketName}/{fileName}`,
    options: {
    credentialsRole: apiGatewayRole,
    requestParameters: {
    'integration.request.path.fileName': 'method.request.querystring.fileName',
    },
    integrationResponses: [{ statusCode: '200' }],
    },
    }),
    options: {
    requestParameters: {
    'method.request.querystring.fileName': true,
    },
    methodResponses: [{
    statusCode: '200',
    }],
    }
    },
    })
    .build(),
    });
    // 后续可以在其他文件中类型安全地访问我们定义的 bucket 属性
    api.integrations.getFile.bucket.grantRead(...);

    您还可以在集成中提供 options 来覆盖特定方法的选项,例如为 getDocumentation 操作使用 Cognito 认证:

    new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this)
    .withOverrides({
    getDocumentation: {
    integration: new HttpIntegration('https://example.com/documentation'),
    options: {
    authorizer: new CognitoUserPoolsAuthorizer(...) // REST API 使用该授权器,HTTP API 使用 HttpUserPoolAuthorizer
    }
    },
    })
    .build(),
    });

    如果不需要默认集成,可以直接为每个操作提供集成。这在需要为不同操作使用不同类型集成时非常有用:

    new MyApi(this, 'MyApi', {
    integrations: {
    sayHello: {
    integration: new LambdaIntegration(...),
    },
    getDocumentation: {
    integration: new HttpIntegration(...),
    },
    },
    });

    如果希望部署单个 Lambda 函数处理所有 API 请求,可以修改 API 的 defaultIntegrations 方法创建共享函数:

    packages/common/constructs/src/app/apis/my-api.ts
    export class MyApi<...> extends ... {
    public static defaultIntegrations = (scope: Construct) => {
    const router = new Function(scope, 'RouterHandler', { ... });
    return IntegrationBuilder.rest({
    ...
    defaultIntegrationOptions: {},
    buildDefaultIntegration: (op) => {
    return {
    // 所有集成引用同一个路由函数
    integration: new LambdaIntegration(router),
    };
    },
    });
    };
    }

    您也可以采用其他自定义方式,例如将 router 函数作为 defaultIntegrations 的参数而非在方法内构造。

    如果选择使用 IAM 身份验证,可以使用 grantInvokeAccess 方法授予对 API 的访问权限。例如,您可能希望授予经过身份验证的 Cognito 用户访问 API 的权限:

    api.grantInvokeAccess(myIdentityPool.authenticatedRole);

    您可以使用 serve 目标运行 API 的本地服务器,例如:

    Terminal window
    pnpm nx run @my-scope/my-api:serve

    本地服务器的入口点是 src/local-server.ts

    在更改 API 时,此服务器会自动重新加载。

    您可以创建 tRPC 客户端以类型安全的方式调用 API。如果从另一个后端调用 tRPC API,可以使用 src/client/index.ts 中的客户端,例如:

    import { createMyApiClient } from ':my-scope/my-api';
    const client = createMyApiClient({ url: 'https://my-api-url.example.com/' });
    await client.echo.query({ message: 'Hello world!' });

    如果从 React 网站调用 API,请考虑使用 API 连接 生成器来配置客户端。

    有关 tRPC 的更多信息,请参阅 tRPC 文档