簡體   English   中英

AWS CDK - 如何將多個 http 方法添加到同一資源

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

對於不同的 HTTP 方法,我如何才能擁有/spaces的標准端點但不同的 lambda 函數?

我希望我能夠使用助手 function

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 如果資源存在,您將跳過重復添加資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM