How can I have a standard endpoint of /spaces
but different lambda functions for different HTTP methods?
I was hoping I'd be able to use a helper 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;
}
And just call it for each resource I want to add
// 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
}
}))
This works well with just one resource, but adding additional will fail with
There is already a Construct with name 'spaces' in RootResource [Default]
Is there a proper pattern for how to do this nicely?
Your method addResource
is performing this.restApi.root.addResource(path)
each time you invoke the method, in your case twice, hence the error about the duplicate.
If you need to keep existing shape of the custom addResource
method, you can verify whether the resource is already defined on given path via https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.Resource.html#getwbrresourcepathpart . If the resource exists you will skip duplicate addition of the resouce.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.