File tree 2 files changed +45
-0
lines changed
2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -8,6 +8,23 @@ import { removeEmpty } from './_util';
8
8
9
9
export class Chart extends Construct {
10
10
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
+
11
28
/**
12
29
* The name of the stack's YAML file as emitted into the cloud assembly
13
30
* directory during synthesis.
Original file line number Diff line number Diff line change @@ -51,6 +51,34 @@ test('tokens are resolved during synth', () => {
51
51
expect ( Testing . synth ( chart ) ) . toMatchSnapshot ( ) ;
52
52
} ) ;
53
53
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 ( / c a n n o t f i n d a p a r e n t c h a r t \( d i r e c t l y o r i n d i r e c t l y \) / ) ;
80
+ } ) ;
81
+
54
82
function createImplictToken ( value : any ) {
55
83
const implicit = { } ;
56
84
Object . defineProperty ( implicit , 'resolve' , { value : ( ) => value } ) ;
You can’t perform that action at this time.
0 commit comments