From 6afa87fe231500805f45abf8ad577e633e435223 Mon Sep 17 00:00:00 2001 From: Elad Ben-Israel Date: Wed, 13 Mar 2019 10:28:34 +0200 Subject: [PATCH] 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 --- .../cdk/lib/cloudformation/condition.ts | 19 +++++++++++++ .../cdk/test/cloudformation/test.condition.ts | 28 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/packages/@aws-cdk/cdk/lib/cloudformation/condition.ts b/packages/@aws-cdk/cdk/lib/cloudformation/condition.ts index 95f4aab398b1d..4d1d8d425ce3a 100644 --- a/packages/@aws-cdk/cdk/lib/cloudformation/condition.ts +++ b/packages/@aws-cdk/cdk/lib/cloudformation/condition.ts @@ -74,4 +74,23 @@ export interface IConditionExpression { * Returns a JSON node that represents this condition expression */ resolve(context: ResolveContext): any; + + /** + * Returns a string token representation of this condition expression, which + * resolves to the CloudFormation condition JSON during synthesis. + * + * You can use `toString` when you wish to embed a condition expression + * in a property value that accepts a `string`. For example: + * + * ```ts + * new sqs.Queue(this, 'MyQueue', { + * queueName: Fn.conditionIf('Condition', 'Hello', 'World').toString() + * }); + * ``` + * + * NOTE: we need this explicitly here despite the fact that in JavaScript this would + * "just work" since conditions are eventually tokens that implement `toString`, + * in order for jsii languages like Java to proxy this to jsii. + */ + toString(): string; } diff --git a/packages/@aws-cdk/cdk/test/cloudformation/test.condition.ts b/packages/@aws-cdk/cdk/test/cloudformation/test.condition.ts index 4ca8300bf25e0..7b69aee3e0aee 100644 --- a/packages/@aws-cdk/cdk/test/cloudformation/test.condition.ts +++ b/packages/@aws-cdk/cdk/test/cloudformation/test.condition.ts @@ -28,5 +28,33 @@ export = { { 'Fn::Not': [ { Condition: 'Condition3' } ] } ] } } }); test.done(); + }, + + 'condition expressions can be embedded as strings'(test: Test) { + // GIVEN + const stack = new cdk.Stack(); + const propValue: string = cdk.Fn.conditionIf('Cond', 'A', 'B').toString(); + + // WHEN + new cdk.Resource(stack, 'MyResource', { + type: 'AWS::Foo::Bar', + properties: { + StringProp: propValue + } + }); + + // THEN + test.ok(cdk.unresolved(propValue)); + test.deepEqual(stack.toCloudFormation(), { + Resources: { + MyResource: { + Type: 'AWS::Foo::Bar', + Properties: { + StringProp: { 'Fn::If': [ 'Cond', 'A', 'B' ] } + } + } + } + }); + test.done(); } };