import * as apigateway from "@aws-cdk/aws-apigateway"; import { Stack } from '@aws-cdk/core'; import { LambdaIntegration } from "@aws-cdk/aws-apigateway"; import Function from '../function'; class APIGateway { readonly resource?: string; readonly gateway: apigateway.RestApi; constructor({ scope, id, name, resource }: { scope: Stack, id: string, name: string, resource?: string }) { const gateway = new apigateway.RestApi( scope, id, { restApiName: name, }, ); this.resource = resource; this.gateway = gateway; if (this.resource) { this.gateway.root.addResource(this.resource); } } stripPath(path: string) { let strippedPath = path; if (path.startsWith('/')) { strippedPath = path.substring(1, path.length); } return strippedPath; } addMethod(method: string, f: Function, path?: string) { const integration = new LambdaIntegration(f); // If a base resource is already defined, find and use that if (this.resource) { const resource = this.gateway.root.getResource(this.resource); if (!resource) { throw new Error(`Resource: ${this.resource} hasn't been correctly registered to the gateway`); } if (path) { resource.addResource(this.stripPath(path)).addMethod(method, integration); return; } resource.addMethod(method, integration); return; } // If we define a custom path, use that as a new resource if (path) { this.gateway.root.addResource(this.stripPath(path)).addMethod(method, integration); return; } // Fallback to adding the method on the root this.gateway.root.addMethod(method, integration); } } export default APIGateway;