Skip to content

Commit

Permalink
Use input as id for unvisitEntity
Browse files Browse the repository at this point in the history
  • Loading branch information
nikita-ushakov committed Oct 1, 2017
1 parent c9c8c8b commit ba1847b
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
17 changes: 17 additions & 0 deletions src/__tests__/__snapshots__/index.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,23 @@ Object {
}
`;

exports[`denormalize denormalizes with function as idAttribute 1`] = `
Array [
Object {
"guest": null,
"id": "1",
"name": "Esther",
},
Object {
"guest": Object {
"guest_id": 1,
},
"id": "2",
"name": "Tom",
},
]
`;

exports[`normalize can use fully custom entity classes 1`] = `
Object {
"entities": Object {
Expand Down
23 changes: 23 additions & 0 deletions src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,4 +224,27 @@ describe('denormalize', () => {
});
expect(() => denormalize('123', article, entities)).not.toThrow();
});

it('denormalizes with function as idAttribute', () => {
const normalizedData = {
'entities': {
'patrons': {
'1': { 'id': '1', 'guest': null, 'name': 'Esther' },
'2': { 'id': '2', 'guest': 'guest-2-1', 'name': 'Tom' }
},
'guests': { 'guest-2-1': { 'guest_id': 1 } }
},
'result': [ '1', '2' ]
};

const guestSchema = new schema.Entity('guests', {}, {
idAttribute: (value, parent, key) => `${key}-${parent.id}-${value.guest_id}`
});

const patronsSchema = new schema.Entity('patrons', {
guest: guestSchema
});

expect(denormalize(normalizedData.result, [ patronsSchema ], normalizedData.entities)).toMatchSnapshot();
});
});
6 changes: 2 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,12 @@ export const normalize = (input, schema) => {
return { entities, result };
};

const unvisitEntity = (input, schema, unvisit, getEntity, cache) => {
const entity = getEntity(input, schema);
const unvisitEntity = (id, schema, unvisit, getEntity, cache) => {
const entity = getEntity(id, schema);
if (typeof entity !== 'object' || entity === null) {
return entity;
}

const id = schema.getId(entity);

if (!cache[schema.key]) {
cache[schema.key] = {};
}
Expand Down

0 comments on commit ba1847b

Please sign in to comment.