Skip to content

Commit

Permalink
Fix parsing relationships in case source data is already Model instance
Browse files Browse the repository at this point in the history
fixes #748
  • Loading branch information
kibertoad authored and koskimas committed Jan 22, 2018
1 parent 43ec07b commit b57d1bf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/model/modelSet.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@ function setJson(model, json, options) {
}

json = model.$parseJson(json, options);
const originalJson = json;
json = model.$validate(json, options);

model.$set(json);

if (!options.skipParseRelations) {
parseRelationsIntoModelInstances(model, json, options);
parseRelationsIntoModelInstances(model, originalJson, options);
}

return model;
Expand Down
36 changes: 36 additions & 0 deletions tests/unit/model/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,42 @@ describe('Model', () => {
expect(json).to.have.property('relation2');
});

it('should parse relations into Model instances if source that is being parsed is already a Model instance', () => {
let Model2 = modelClass('Model2');

Model1.relationMappings = {
relation1: {
relation: Model.HasManyRelation,
modelClass: Model2,
join: {
from: 'Model1.id',
to: 'Model2.model1Id'
}
},
relation2: {
relation: Model.BelongsToOneRelation,
modelClass: Model1,
join: {
from: 'Model1.id',
to: 'Model1.model1Id'
}
}
};

let model = Model1.fromJson({
id: 10,
model1Id: 13
});
model.relation1 = [{ id: 11, model1Id: 10 }, { id: 12, model1Id: 10 }];
model.relation2 = { id: 13, model1Id: null };

let modelWithRelationships = Model1.fromJson(model);

expect(modelWithRelationships.relation1[0]).to.be.a(Model2);
expect(modelWithRelationships.relation1[1]).to.be.a(Model2);
expect(modelWithRelationships.relation2).to.be.a(Model1);
});

it('should NOT parse relations into Model instances if skipParseRelations option is given', () => {
let Model2 = modelClass('Model2');

Expand Down

0 comments on commit b57d1bf

Please sign in to comment.