Skip to content

Commit

Permalink
feat(core): node.defaultChild as a shortcut to escape hatch (#2684)
Browse files Browse the repository at this point in the history
Convenience property which returns the child with id "Resource"
or "Default" (fails if there are both).

This is useful in order to enable escape hatching.

Closes #2290
  • Loading branch information
Elad Ben-Israel committed May 30, 2019
1 parent f2636e5 commit 8cd3c23
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/@aws-cdk/cdk/lib/construct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,21 @@ export class ConstructNode {
return ret;
}

/**
* Returns the child construct that has the id "Default" or "Resource".
* @throws if there is more than one child
* @returns a construct or undefined if there is no default child
*/
public get defaultChild(): IConstruct | undefined {
const resourceChild = this.tryFindChild('Resource');
const defaultChild = this.tryFindChild('Default');
if (resourceChild && defaultChild) {
throw new Error(`Cannot determine default child for ${this.path}. There is both a child with id "Resource" and id "Default"`);
}

return defaultChild || resourceChild;
}

/**
* All direct children of this construct.
*/
Expand Down
41 changes: 41 additions & 0 deletions packages/@aws-cdk/cdk/test/test.construct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,47 @@ export = {
test.ok(child2.node.root === root);
test.ok(child1_1_1.node.root === root);
test.done();
},

'defaultChild': {
'returns the child with id "Resource"'(test: Test) {
const root = new Root();
new Construct(root, 'child1');
const defaultChild = new Construct(root, 'Resource');
new Construct(root, 'child2');

test.same(root.node.defaultChild, defaultChild);
test.done();
},
'returns the child with id "Default"'(test: Test) {
const root = new Root();
new Construct(root, 'child1');
const defaultChild = new Construct(root, 'Default');
new Construct(root, 'child2');

test.same(root.node.defaultChild, defaultChild);
test.done();
},
'returns "undefined" if there is no default'(test: Test) {
const root = new Root();
new Construct(root, 'child1');
new Construct(root, 'child2');

test.equal(root.node.defaultChild, undefined);
test.done();
},
'fails if there are both "Resource" and "Default"'(test: Test) {
const root = new Root();
new Construct(root, 'child1');
new Construct(root, 'Default');
new Construct(root, 'child2');
new Construct(root, 'Resource');

test.throws(() => root.node.defaultChild,
/Cannot determine default child for . There is both a child with id "Resource" and id "Default"/);
test.done();

}
}
};

Expand Down

0 comments on commit 8cd3c23

Please sign in to comment.