Skip to content

Commit

Permalink
feat(cloudwatch): dashboardName validation (#3382)
Browse files Browse the repository at this point in the history
Fixes #2976
  • Loading branch information
Jimmy Gaussen authored and Elad Ben-Israel committed Jul 23, 2019
1 parent 5a6aff0 commit f53f845
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
18 changes: 15 additions & 3 deletions packages/@aws-cdk/aws-cloudwatch/lib/dashboard.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Construct, Lazy, Resource, Stack } from "@aws-cdk/core";
import { Construct, Lazy, Resource, Stack, Token } from "@aws-cdk/core";
import { CfnDashboard } from './cloudwatch.generated';
import { Column, Row } from "./layout";
import { IWidget } from "./widget";
Expand All @@ -10,9 +10,11 @@ export enum PeriodOverride {

export interface DashboardProps {
/**
* Name of the dashboard
* Name of the dashboard.
*
* @default Automatically generated name
* If set, must only contain alphanumerics, dash (-) and underscore (_)
*
* @default - automatically generated name
*/
readonly dashboardName?: string;

Expand Down Expand Up @@ -67,6 +69,16 @@ export class Dashboard extends Resource {
physicalName: props.dashboardName,
});

{
const {dashboardName} = props;
if (dashboardName && !Token.isUnresolved(dashboardName) && !dashboardName.match(/^[\w-]+$/)) {
throw new Error([
`The value ${dashboardName} for field dashboardName contains invalid characters.`,
'It can only contain alphanumerics, dash (-) and underscore (_).'
].join(' '));
}
}

new CfnDashboard(this, 'Resource', {
dashboardName: this.physicalName,
dashboardBody: Lazy.stringValue({ produce: () => {
Expand Down
18 changes: 18 additions & 0 deletions packages/@aws-cdk/aws-cloudwatch/test/test.dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,24 @@ export = {
// THEN
expect(stack).to(haveResource('AWS::CloudWatch::Dashboard', {}));

test.done();
},

'throws if DashboardName is not valid'(test: Test) {
// GIVEN
const app = new App();
const stack = new Stack(app, 'MyStack');

// WHEN
const toThrow = () => {
new Dashboard(stack, 'MyDashboard', {
dashboardName: 'My Invalid Dashboard Name',
});
};

// THEN
test.throws(() => toThrow(), /field dashboardName contains invalid characters/);

test.done();
}
};
Expand Down

0 comments on commit f53f845

Please sign in to comment.