Skip to content

Commit

Permalink
Merge pull request #286 from jomendez/ignore-getters
Browse files Browse the repository at this point in the history
fix: Getter methods decorated with @ignore() should not be present
  • Loading branch information
wovalle committed Nov 17, 2021
2 parents 7b61dbd + 8cd92ba commit e987b49
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
25 changes: 25 additions & 0 deletions src/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,31 @@ describe('Utils', () => {
expect(serializeEntity(rhcp, [])).not.toHaveProperty('temporaryName');
});

it('should not return getter properties with an Ignore() decorator', () => {
class Band implements IEntity {
id: string;
name: string;

get removeFirstLetterOfName() {
if (!this.name) return '';
return this.name.charAt(0);
}

@Ignore()
get capitalizedName() {
if (!this.name) return '';
return this.name.charAt(0).toUpperCase() + this.name.slice(1);
}
}

const rhcp = new Band();
rhcp.name = 'red Hot Chili Peppers';

expect(serializeEntity(rhcp, [])).toHaveProperty('name');
expect(serializeEntity(rhcp, [])).toHaveProperty('removeFirstLetterOfName');
expect(serializeEntity(rhcp, [])).not.toHaveProperty('capitalizedName');
});

it('should serialize object properties with the @Serialize() decorator', () => {
class Address {
streetName: string;
Expand Down
5 changes: 1 addition & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,10 @@ export function serializeEntity<T extends IEntity>(
delete serializableObj[scm.propertyKey];
});

Object.keys(obj).forEach(propertyKey => {
Object.entries(serializableObj).forEach(([propertyKey, propertyValue]) => {
if (Reflect.getMetadata(ignoreKey, obj, propertyKey) === true) {
delete serializableObj[propertyKey];
}
});

Object.entries(serializableObj).forEach(([propertyKey, propertyValue]) => {
if (Reflect.getMetadata(serializeKey, obj, propertyKey) !== undefined) {
if (Array.isArray(propertyValue)) {
(serializableObj as { [key: string]: unknown })[propertyKey] = propertyValue.map(element =>
Expand Down

0 comments on commit e987b49

Please sign in to comment.