AWS CDK - 如何将多个 http 方法添加到同一资源

AWS CDK - How to add multiple http methods to the same resource

我怎样才能拥有 /spaces 的标准端点,但不同的 HTTP 方法有不同的 lambda 函数?

我希望我能够使用辅助函数

addResource(path: string, method: HttpMethods, lambda: lambda.Function) {
  const lambdaIntegration: LambdaIntegration = new LambdaIntegration(lambda, { proxy: true });
  const resource: Resource = this.restApi.root.addResource(path);

  resource.addMethod(method, lambdaIntegration, {
    authorizationType: AuthorizationType.IAM,
  });

  return resource;
}

并且只需为我要添加的每个资源调用它

// POST - spaces
gateway.addResource('spaces', HttpMethods.POST, new Function(this, 'droppixel-space-post', {
    runtime: Runtime.NODEJS_12_X,
    code: Code.fromAsset(`${__dirname}/../lambda-fns/space-api/src`),
    handler: 'create.handler',
    environment: {
        TABLE: table.table.tableArn
    }
}))

// GET - spaces
gateway.addResource('spaces', HttpMethods.GET, new Function(this, 'droppixel-space-get', {
    runtime: Runtime.NODEJS_12_X,
    code: Code.fromAsset(`${__dirname}/../lambda-fns/space-api/src`),
    handler: 'list.handler',
    environment: {
        TABLE: table.table.tableArn
    }
}))

这只适用于一种资源,但添加其他资源会失败

There is already a Construct with name 'spaces' in RootResource [Default]

有没有合适的模式来很好地做到这一点?

您的方法 addResource 每次调用该方法时都会执行 this.restApi.root.addResource(path),在您的例子中是两次,因此会出现关于重复的错误。

如果您需要保留自定义 addResource 方法的现有形状,您可以通过 https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.Resource.html#getwbrresourcepathpart 验证资源是否已在给定路径上定义。如果资源存在,您将跳过重复添加资源。