Skip to content

Commit

Permalink
fix(cdk-dasm): prevent duplicate imports (#5293)
Browse files Browse the repository at this point in the history
Signed-off-by: campionfellin <campionfellin@gmail.com>
  • Loading branch information
campionfellin authored and mergify[bot] committed Dec 4, 2019
1 parent ec83ebb commit d4562b7
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
10 changes: 7 additions & 3 deletions packages/cdk-dasm/lib/dasm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ export async function dasmTypeScript(template: Template, options: DisassemblerOp

code.line(`import { Stack, StackProps, Construct, Fn } from '@aws-cdk/core';`);

for (const def of definitions) {
const importName = `@aws-cdk/aws-${def.namespace}`;
code.line(`import ${def.namespace} = require('${importName}');`);
for (const ns of getUniqueNamespaces(definitions)) {
const importName = `@aws-cdk/aws-${ns}`;
code.line(`import ${ns} = require('${importName}');`);
}

code.line();
Expand Down Expand Up @@ -143,6 +143,10 @@ function toCfnClassName(resourceType: string) {
return { namespace: namespace.toLocaleLowerCase(), className };
}

function getUniqueNamespaces(definitions: Array<ConstructDefinition>): String[] {
return [... new Set(definitions.map(definition => definition.namespace))];
}

interface Template {
Resources: { [id: string]: Resource };
}
Expand Down
20 changes: 20 additions & 0 deletions packages/cdk-dasm/test/__snapshots__/dasm.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,26 @@ export class MyStack extends Stack {
"
`;

exports[`multiple of same type 1`] = `
"// generated by cdk-dasm
import { Stack, StackProps, Construct, Fn } from '@aws-cdk/core';
import sns = require('@aws-cdk/aws-sns');
export class MyStack extends Stack {
constructor(scope: Construct, id: string, props: StackProps = {}) {
super(scope, id, props);
new sns.CfnTopic(this, 'MyTopic', {
displayName: \\"hello hello\\",
});
new sns.CfnTopic(this, 'MyTopicDos', {
displayName: \\"hello again\\",
});
}
}
"
`;

exports[`no props 1`] = `
"// generated by cdk-dasm
Expand Down
19 changes: 19 additions & 0 deletions packages/cdk-dasm/test/dasm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,25 @@ test('no props', async () => {
})).toMatchSnapshot();
});

test('multiple of same type', async () => {
expect(await dasm({
Resources: {
MyTopic: {
Type: 'AWS::SNS::Topic',
Properties: {
DisplayName: 'hello hello'
}
},
MyTopicDos: {
Type: 'AWS::SNS::Topic',
Properties: {
DisplayName: 'hello again'
}
}
}
})).toMatchSnapshot();
});

test('bucket-and-key', async () => {
expect(await dasm(require('./bucket-key.json'))).toMatchSnapshot();
});
Expand Down

0 comments on commit d4562b7

Please sign in to comment.