I am a beginner at TS manipulation with ts-morph.
I have a template of existing source file, and i wanted to continue building up the template within the constructor space within the main class.
cdk-gen-stack.ts
export class CdkGenStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
//to insert code below
}
}
ts-morph.ts
import * as tsmorph from "ts-morph";
const project = new tsmorph.Project({
tsConfigFilePath: "tsconfig.json",
});
const sourceFile = project.getSourceFile("lib/cdk-gen-stack.ts");
const mainClasses = sourceFile?.getClass("CdkGenStack");
const mainConstructor = mainClasses?.getConstructors();
sourceFile?.save();
I am stuck as I am not sure what I could do after getting the constructor from the main class. What I want to achieve for example within the main template within the main class and constructor:
cdk-gen-stack.ts (morphed)
export class CdkGenStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// I want to start inserting something here, for example:
const table = new dynamodb.Table(this, 'Table', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING }
});
}
}
I have spent a lot of time researching online and trying to get any existing methods I can use with the constructor. There are addMethods and addVariable for classes, for example mainClasses?.addMember("test"); or:
mainClasses?.set({
ctors: [{
statements: [
"test"
]
}]
});
However these will insert them outside the constructor. What I want is to insert it within the given constructor that already exists in the class.