Skip to content

Commit 6afa87f

Browse files
author
Elad Ben-Israel
authored
fix(core): allow embedding condition expression as strings (#2007)
Expose the underlying `toString` in the `IConditionExpression` interface so they can be embedded as string values in jsii languages. Fixes #1984
1 parent 946b444 commit 6afa87f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

packages/@aws-cdk/cdk/lib/cloudformation/condition.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,23 @@ export interface IConditionExpression {
7474
* Returns a JSON node that represents this condition expression
7575
*/
7676
resolve(context: ResolveContext): any;
77+
78+
/**
79+
* Returns a string token representation of this condition expression, which
80+
* resolves to the CloudFormation condition JSON during synthesis.
81+
*
82+
* You can use `toString` when you wish to embed a condition expression
83+
* in a property value that accepts a `string`. For example:
84+
*
85+
* ```ts
86+
* new sqs.Queue(this, 'MyQueue', {
87+
* queueName: Fn.conditionIf('Condition', 'Hello', 'World').toString()
88+
* });
89+
* ```
90+
*
91+
* NOTE: we need this explicitly here despite the fact that in JavaScript this would
92+
* "just work" since conditions are eventually tokens that implement `toString`,
93+
* in order for jsii languages like Java to proxy this to jsii.
94+
*/
95+
toString(): string;
7796
}

packages/@aws-cdk/cdk/test/cloudformation/test.condition.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,33 @@ export = {
2828
{ 'Fn::Not': [ { Condition: 'Condition3' } ] } ] } } });
2929

3030
test.done();
31+
},
32+
33+
'condition expressions can be embedded as strings'(test: Test) {
34+
// GIVEN
35+
const stack = new cdk.Stack();
36+
const propValue: string = cdk.Fn.conditionIf('Cond', 'A', 'B').toString();
37+
38+
// WHEN
39+
new cdk.Resource(stack, 'MyResource', {
40+
type: 'AWS::Foo::Bar',
41+
properties: {
42+
StringProp: propValue
43+
}
44+
});
45+
46+
// THEN
47+
test.ok(cdk.unresolved(propValue));
48+
test.deepEqual(stack.toCloudFormation(), {
49+
Resources: {
50+
MyResource: {
51+
Type: 'AWS::Foo::Bar',
52+
Properties: {
53+
StringProp: { 'Fn::If': [ 'Cond', 'A', 'B' ] }
54+
}
55+
}
56+
}
57+
});
58+
test.done();
3159
}
3260
};

0 commit comments

Comments
 (0)