TL;DR: What is the purpose and function of prepare(): void
method of AWS CDK's Construct
class? How and when am I supposed to use/avoid it?
The documentation on prepare()
says:
protected prepare(): voidPerform final modifications before synthesis.
This method can be implemented by derived constructs in order to perform final changes before synthesis. prepare() will be called after child constructs have been prepared.
This is an advanced framework feature. Only use this if you understand the implications.
… but those "implications" are nowhere to be found.
Judging by a couple of AWS CDK projects I saw (such as this one), when AWS CDK constructs and stacks are built, all of their internal structure (mainly, child constructs) is set up exclusively in the constructor()
function (this would be a typical example of that).
I don't think this is a good way of using classes, but I couldn't see another way of setting up stacks and constructs for a long time. However, recently I stumbled upon prepare()
and its description ("…will be called after child constructs have been prepared"). I guessed, that it is supposed to be used like so:
export class SomeStack extends AWS.Stack {
prepare() {
// add constructs
// set permissions
// basically, do everything that is done in `constructor()` here: https://github.com/aws-samples/aws-cdk-examples/blob/master/typescript/api-cors-lambda-crud-dynamodb/index.ts
}
}
… but this doesn't fit very well with the phrasing "perform final modifications" from the method description.