I'm fairly new to CDK and I've tried migrating something from vanilla JavaScript to TypeScript, in doing so trying to make it a little more modular. This is the current structure that I've got:
CdkStack.ts
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// API Gateway
const api = new API(scope, "API");
}
Api.ts
export class API extends Construct {
public restApi: RestApi;
constructor(scope: Construct, id: string) {
super(scope, id);
const restApi = new RestApi(this, "website-api", {
restApiName: "website-api",
description: "This service provides API calls for the website.",
});
const getListLambda = new GetListLambda(
scope,
"GetListLambda"
);
const listApi = restApi.root.addResource("list");
listApi.addMethod("GET", getListLambda.integration); // GET /
}
}
GetListLambda.ts
export class GetListLambda extends Construct {
public lambdaFunction: Function;
public integration: LambdaIntegration;
constructor(scope: Construct, id: string) {
super(scope, id);
this.lambdaFunction = new Function(this, "GetListLambda", {
runtime: Runtime.NODEJS_12_X,
code: new AssetCode("lambdas/getList", {
exclude: ["*.local.js", "*.test.js"],
}),
handler: "index.handler",
environment,
});
this.integration = new LambdaIntegration(this.lambdaFunction, {
proxy: true,
});
}
}
I used to have basically the same code, but all in a single file. With this current structure I get the following output when I try to do a deploy:
No stack could be identified for the construct at path API/website-api
/src/api/node_modules/@aws-cdk/aws-apigateway/lib/restapi.ts:540 if (this.methods.length === 0) { ^ TypeError: Cannot read property 'length' of undefined at RestApi.validate (/src/api/node_modules/@aws-cdk/aws-apigateway/lib/restapi.ts:540:22) at RestApi.onValidate (/src/api/node_modules/@aws-cdk/core/lib/construct-compat.ts:97:17) at Node.validate (/src/api/node_modules/constructs/lib/construct.ts:445:54) at Node.validate (/src/api/node_modules/constructs/lib/construct.ts:442:45) at Node.validate (/src/api/node_modules/constructs/lib/construct.ts:442:45) at Node.synthesize (/src/api/node_modules/constructs/lib/construct.ts:391:27) at Function.synth (/src/api/node_modules/@aws-cdk/core/lib/construct-compat.ts:231:22) at App.synth (/src/api/node_modules/@aws-cdk/core/lib/app.ts:142:36) at process. (/src/api/node_modules/@aws-cdk/core/lib/app.ts:121:45) at Object.onceWrapper (events.js:422:26)
The error reads as though there aren't any methods, however I've clearly added a method to the API.
const api = new API(this, "API");
instead, to pass down the reference to the stack for the underlying modules? – dmahapatro