Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): node.defaultChild as shortcut to escape hatch #2684

Merged
merged 1 commit into from
May 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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