Applicable when
- API Gateway is used to support client API calls
- The expected number of resources is not huge (<60 resources)
Non-applicable when
- A large number of resources is expected (You will need to split stacks in that case)
Implementation
The code below will create a new nested stack with configured API Gateway and utility method to easily add new resources
import { MethodLoggingLevel, Resource, RestApi } from '@aws-cdk/aws-apigateway';
import { NestedStack, NestedStackProps } from '@aws-cdk/aws-cloudformation';
import { Construct } from '@aws-cdk/core';
import { withEnv } from '../util/consts';
export class RestApiStack extends NestedStack {
public api: RestApi;
public deployment: Deployment;
constructor(scope: Construct, id: string, props?: NestedStackProps) {
super(scope, id, props);
this.api = new RestApi(this, withEnv('rest-api'), {
deployOptions: {
loggingLevel: MethodLoggingLevel.ERROR,
},
});
}
public getResource(path: string): Resource {
const parts = path.split('/');
let currentNode = this.api.root;
for (const part of parts) {
currentNode = currentNode.getResource(part) ?? currentNode.addResource(part);
}
return currentNode as Resource;
}
}
Usage example
export class BackendStack extends Stack {
constructor(scope: App, id: string, props?: StackProps) {
super(scope, id, props);
const restAPI = new RestApiStack(this, withEnv('rest-api-stack'));
...
restAPI
.getResource('servers/{serverId}/users/{username}/config')
.addMethod('GET', new LambdaIntegration(lambdaFunction, { proxy: true }));
}
}
Comments
0 comments
Please sign in to leave a comment.