Skip to content

Commit

Permalink
fix(core): add prototype properties (getters, setters) to destination…
Browse files Browse the repository at this point in the history
…Path

fix #334
  • Loading branch information
Chau Tran authored and Chau Tran committed Aug 22, 2021
1 parent b1ff198 commit 15ad713
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import { uniquePaths } from '../utils';

const EXCLUDE_KEYS = [
'constructor',
'__defineGetter__',
'__defineSetter__',
'hasOwnProperty',
'__lookupGetter__',
'__lookupSetter__',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'valueOf',
'__proto__',
'toLocaleString',
];

/**
* Loop through an object and recursively get paths of each property
*
Expand All @@ -19,7 +34,17 @@ export function getPathRecursive(
const result = prev;
let hadChildPaths = false;

const keys = Object.getOwnPropertyNames(node);
const ownPropertyNames = Object.getOwnPropertyNames(node);
const prototype = Object.getPrototypeOf(node);
const prototypeOwnPropertyNames = prototype
? Object.keys(Object.getOwnPropertyDescriptors(prototype)).filter(
(key) => !EXCLUDE_KEYS.includes(key)
)
: [];

const keys = Array.from(
new Set([...ownPropertyNames, ...prototypeOwnPropertyNames])
);
for (let i = 0, len = keys.length; i < len; i++) {
const key = keys[i];
const path: string[] = [...prefix, key];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ describe('getPathRecursive', () => {
['.startDot']: undefined,
['endDot.']: undefined,
},
_privateFoo: undefined,
get privateFoo() {
return this._privateFoo;
},
};

const resultPaths = [
Expand All @@ -36,6 +40,8 @@ describe('getPathRecursive', () => {
['mid.Dot'],
['mid.Dot', '.startDot'],
['mid.Dot', 'endDot.'],
['_privateFoo'],
['privateFoo'],
];

it('should work', () => {
Expand Down
12 changes: 12 additions & 0 deletions packages/integration-test/src/lib/with-classes/variants.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ describe('Variants', () => {
expect(vm.fullName).toEqual(user.firstName + ' ' + user.lastName);
});

it('should map back to model with getters', () => {
mapper.createMap(SimpleUserVm, UserWithGetter);

const simpleUser = new SimpleUserVm();
simpleUser.firstName = 'Chau';
simpleUser.lastName = 'Tran';

const user = mapper.map(simpleUser, UserWithGetter, SimpleUserVm);
expect(user.firstName).toEqual(simpleUser.firstName);
expect(user.lastName).toEqual(simpleUser.lastName);
});

it('should map with model with ONLY getters', () => {
mapper.createMap(UserWithOnlyGetter, SimpleUserVm).forMember(
(d) => d.fullName,
Expand Down

0 comments on commit 15ad713

Please sign in to comment.