Skip to content

Commit d6a9dc0

Browse files
author
Elad Ben-Israel
committed
feat: Chart.of(node)
Finds the chart in which a construct node is defined. Throws if the node is not defined within a chart (directly or indirectly).
1 parent d6250be commit d6a9dc0

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

packages/cdk8s/lib/chart.ts

+17
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,23 @@ import { removeEmpty } from './_util';
88

99
export class Chart extends Construct {
1010

11+
/**
12+
* Finds the chart in which a node is defined.
13+
* @param node a construct node
14+
*/
15+
public static of(node: Construct): Chart {
16+
if (node instanceof Chart) {
17+
return node;
18+
}
19+
20+
const parent = node.node.scope as Construct;
21+
if (!parent) {
22+
throw new Error(`cannot find a parent chart (directly or indirectly)`);
23+
}
24+
25+
return Chart.of(parent);
26+
}
27+
1128
/**
1229
* The name of the stack's YAML file as emitted into the cloud assembly
1330
* directory during synthesis.

packages/cdk8s/test/chart.test.ts

+28
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,34 @@ test('tokens are resolved during synth', () => {
5151
expect(Testing.synth(chart)).toMatchSnapshot();
5252
});
5353

54+
test('Chart.of(node) returns the first chart in which a node is defined', () => {
55+
// GIVEN
56+
const app = new App();
57+
58+
// WHEN
59+
const chart = new Chart(app, 'MyFirst');
60+
const direct = new Construct(chart, 'Direct');
61+
const indirect = new Construct(direct, 'Indirect');
62+
63+
const childChart = new Chart(indirect, 'ChildChart');
64+
const childChild = new Construct(childChart, 'ChildChild');
65+
66+
expect(Chart.of(chart)).toEqual(chart);
67+
expect(Chart.of(direct)).toEqual(chart);
68+
expect(Chart.of(indirect)).toEqual(chart);
69+
expect(Chart.of(childChart)).toEqual(childChart);
70+
expect(Chart.of(childChild)).toEqual(childChart);
71+
});
72+
73+
test('Chart.of(node) fails when there is no chart in the tree', () => {
74+
// GIVEN
75+
const app = new App();
76+
const child = new Construct(app, 'MyConstruct');
77+
78+
// WHEN
79+
expect(() => Chart.of(child)).toThrow(/cannot find a parent chart \(directly or indirectly\)/);
80+
});
81+
5482
function createImplictToken(value: any) {
5583
const implicit = {};
5684
Object.defineProperty(implicit, 'resolve', { value: () => value });

0 commit comments

Comments
 (0)