Skip to content

Commit

Permalink
fix(core): Duration.toString() throws an error (#18243)
Browse files Browse the repository at this point in the history
`Duration.toString()` was intended to produce a value that would throw an exception when resolved,
but unintentionally was written to always throw immediately (the reason it was throwing is that `Token.asString()`
doesn't accept functions, it only accepts data values--`Lazy.string()` should have been used).

Instead, we remove the validation completely. `toString()` now produces a meaningless string, and users
should avoid using the `Duration` object in a context where it will be implicitly converted to a string.

Fixes #18176.


----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
rix0rrr authored Jan 3, 2022
1 parent 2868f1d commit df03df8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
14 changes: 5 additions & 9 deletions packages/@aws-cdk/core/lib/duration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,17 +220,13 @@ export class Duration {
}

/**
* Returns a string representation of this `Duration` that is also a Token that cannot be successfully resolved. This
* protects users against inadvertently stringifying a `Duration` object, when they should have called one of the
* `to*` methods instead.
* Returns a string representation of this `Duration`
*
* This is is never the right function to use when you want to use the `Duration`
* object in a template. Use `toSeconds()`, `toMinutes()`, `toDays()`, etc. instead.
*/
public toString(): string {
return Token.asString(
() => {
throw new Error('Duration.toString() was used, but .toSeconds, .toMinutes or .toDays should have been called instead');
},
{ displayHint: `${this.amount} ${this.unit.label}` },
);
return `Duration.${this.unit.label}(${this.amount})`;
}

/**
Expand Down
4 changes: 3 additions & 1 deletion packages/@aws-cdk/core/test/duration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import { Duration, Lazy, Stack, Token } from '../lib';
describe('duration', () => {
test('negative amount', () => {
expect(() => Duration.seconds(-1)).toThrow(/negative/);
});


test('can stringify', () => {
expect(`${Duration.hours(1)}`).toEqual('Duration.hours(1)');
});

test('unresolved amount', () => {
Expand Down

0 comments on commit df03df8

Please sign in to comment.