|
1 | 1 | import { Construct } from 'constructs';
|
2 |
| -import { aws_sqs as sqs } from 'aws-cdk-lib'; |
3 |
| - |
4 |
| -export type ConstructCognitoProps = { |
5 |
| - includeQueue?: boolean; |
6 |
| -}; |
| 2 | +import * as lambda from 'aws-cdk-lib/aws-lambda'; |
| 3 | +import * as apigateway from 'aws-cdk-lib/aws-apigateway'; |
| 4 | +import { RestApiConstructProps } from './types.js'; |
7 | 5 |
|
8 | 6 | /**
|
9 |
| - * Hello world construct implementation |
| 7 | + * Rest API construct for Amplify Backend |
10 | 8 | */
|
11 |
| -export class AmplifyConstruct extends Construct { |
| 9 | +export class RestApiConstruct extends Construct { |
| 10 | + public readonly api: apigateway.RestApi; |
12 | 11 | /**
|
13 |
| - * Create a new AmplifyConstruct |
| 12 | + * Create a new RestApiConstruct |
14 | 13 | */
|
15 |
| - constructor(scope: Construct, id: string, props: ConstructCognitoProps = {}) { |
| 14 | + constructor(scope: Construct, id: string, props: RestApiConstructProps) { |
16 | 15 | super(scope, id);
|
17 | 16 |
|
18 |
| - if (props.includeQueue) { |
19 |
| - new sqs.Queue(this, 'placeholder'); |
| 17 | + // Create a new Lambda function for the API Gateway |
| 18 | + const handler = new lambda.Function(this, 'handler', { |
| 19 | + runtime: lambda.Runtime.NODEJS_18_X, |
| 20 | + handler: 'index.handler', |
| 21 | + code: lambda.Code.fromAsset(props.lambdaEntry), |
| 22 | + }); |
| 23 | + |
| 24 | + // Create a new API Gateway REST API with the specified name |
| 25 | + this.api = new apigateway.RestApi(this, 'RestApi', { |
| 26 | + restApiName: props.apiName, |
| 27 | + }); |
| 28 | + |
| 29 | + // Create a resource for the specified path |
| 30 | + const resource = this.addNestedResource(this.api.root, props.path); |
| 31 | + |
| 32 | + // Add methods to the resource for each HTTP method specified in props.routes |
| 33 | + for (const method of props.routes) { |
| 34 | + resource.addMethod(method, new apigateway.LambdaIntegration(handler)); |
20 | 35 | }
|
21 | 36 | }
|
| 37 | + |
| 38 | + /** |
| 39 | + * Adds nested resources to the API based on the provided path. |
| 40 | + */ |
| 41 | + private addNestedResource( |
| 42 | + root: apigateway.IResource, |
| 43 | + path: string, |
| 44 | + ): apigateway.IResource { |
| 45 | + return path.split('/').reduce((resource, part) => { |
| 46 | + return resource.getResource(part) ?? resource.addResource(part); |
| 47 | + }, root); |
| 48 | + } |
22 | 49 | }
|
0 commit comments