【问题标题】:AWS CDK - How to add multiple http methods to the same resourceAWS CDK - 如何将多个 http 方法添加到同一资源
【发布时间】:2021-01-30 12:53:01
【问题描述】:

我如何才能拥有/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]

是否有适当的模式可以很好地做到这一点?

【问题讨论】:

    标签: typescript aws-cdk


    【解决方案1】:

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

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

    【讨论】:

    • 我也遇到了同样的错误。 public addCorsOptions(apiResource: apigw.IResource) { apiResource.addMethod( "OPTIONS",. 有什么建议吗?你能详细点吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2011-04-11
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多