Skip to content

Commit 2fc2d89

Browse files
committed
Merge branch 'defineApi_construct' of https://github.com/bennettsf/amplify-backend into testing-branch
2 parents 1dedd18 + 71052e0 commit 2fc2d89

File tree

2 files changed

+53
-11
lines changed

2 files changed

+53
-11
lines changed
Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,49 @@
11
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';
75

86
/**
9-
* Hello world construct implementation
7+
* Rest API construct for Amplify Backend
108
*/
11-
export class AmplifyConstruct extends Construct {
9+
export class RestApiConstruct extends Construct {
10+
public readonly api: apigateway.RestApi;
1211
/**
13-
* Create a new AmplifyConstruct
12+
* Create a new RestApiConstruct
1413
*/
15-
constructor(scope: Construct, id: string, props: ConstructCognitoProps = {}) {
14+
constructor(scope: Construct, id: string, props: RestApiConstructProps) {
1615
super(scope, id);
1716

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));
2035
}
2136
}
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+
}
2249
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export type RestApiConstructProps = {
2+
apiName: string;
3+
path: string;
4+
routes: HttpMethod[];
5+
lambdaEntry: string;
6+
};
7+
8+
export type HttpMethod =
9+
| 'GET'
10+
| 'POST'
11+
| 'PUT'
12+
| 'DELETE'
13+
| 'PATCH'
14+
| 'HEAD'
15+
| 'OPTIONS';

0 commit comments

Comments
 (0)