"prepare" AWS CDK 构造方法的用途?

Purpose of "prepare" method of AWS CDK constructs?

TL;DR:AWS CDK的Constructclass的prepare(): void方法的目的和作用是什么?我应该如何以及何时 use/avoid 它?


documentation on prepare() 说:

protected prepare(): void

Perform 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.

……但那些“暗示”无处可寻


根据我看到的几个 AWS CDK 项目(例如 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)判断。

我认为这不是使用 classes 的好方法,但很长一段时间我都看不到另一种设置堆栈和构造的方法。然而,最近我偶然发现了 prepare() 及其描述(“……将在准备好子构造后调用”)。我猜,它应该像这样使用:

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
  }
}

…但这与方法描述中的措辞“执行最终修改”不太吻合。

我有 an answer from one of the contributors of aws-cdk.

正如他们所指出的那样,prepare() 已被弃用,并且即将被删除,因此没有必要使用它:

I think the most important implication is constructs you add during the execution of this method will themselves not be prepared (so you shouldn't be adding any constructs that rely on that happening).

prepare is a method of last resort, for constructs to fix up their own state just before rendering in some conditions (for example, to render default values if certain mutator methods did not get called).

prepare() is deprecated and will be removed in v2. I would not suggest relying on it.

至于在构造函数中设置所有内容,建议将内部构造的定义视为给定父构造初始化的一部分:

I understand you might have psychological aversion to doing a lot of work in the constructor. Try to see construct definitions like a set of declarations that just happen to produce an initialized object (where our Stack definitely has a Table and the compiler can verify that this member got assigned in the constructor so we can rely on this in the rest of the program).