Skip to content

Commit

Permalink
fix: renaming property does not remove old property (#157)
Browse files Browse the repository at this point in the history
The following pseud-code would incorrectly result in a struct containing `newProp` and `oldProp`.

```ts
  struct.add({ name: 'oldProp' });
  struct.rename('oldProp', 'newProp');
```
  • Loading branch information
mrgrain authored Oct 5, 2023
1 parent 7ee55ff commit 2c84763
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/builder/struct.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export class Struct implements IStructBuilder, HasProperties, HasFullyQualifiedN
const old = this._properties.get(name);

if (!old) {
throw `Unable top update property '${name}' in '${this._base.fqn}: Property does not exists, please use \`add\`.'`;
throw `Unable to update property '${name}' in '${this._base.fqn}: Property does not exists, please use \`add\`.'`;
}

const updatedProp = {
Expand All @@ -200,6 +200,10 @@ export class Struct implements IStructBuilder, HasProperties, HasFullyQualifiedN
},
};

if (updatedProp.name !== name) {
this.omit(name);
}

return this.add(updatedProp);
}

Expand Down
12 changes: 12 additions & 0 deletions test/projen/__snapshots__/projen-struct.test.ts.snap

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions test/projen/projen-struct.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,30 @@ test('can updateAll props', () => {
expect(renderedFile).toMatchSnapshot();
});

test('can rename a prop', () => {
// ARRANGE
const project = new TestProject();

// ACT
const struct = new ProjenStruct(project, { name: 'MyInterface' });
struct.add(
{
name: 'oldProp',
type: { primitive: PrimitiveType.Boolean },
optional: true,
},
);
struct.rename('oldProp', 'newProp');

// PREPARE
const renderedFile = synthSnapshot(project)['src/MyInterface.ts'];

// ASSERT
expect(renderedFile).not.toContain('oldProp');
expect(renderedFile).toContain('newProp?: boolean');
expect(renderedFile).toMatchSnapshot();
});

test('can import type from the same package at the top level', () => {
// ARRANGE
const project = new TestProject();
Expand Down

0 comments on commit 2c84763

Please sign in to comment.