Skip to content

Commit

Permalink
Handle relationships as well.
Browse files Browse the repository at this point in the history
  • Loading branch information
luketheobscure committed Jan 15, 2020
1 parent 6170b40 commit f2aa827
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
14 changes: 10 additions & 4 deletions addon/utils/merge-deep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,16 @@ function propertyIsOnObject(object: any, property: any) {
}
}

// Ember Data models don't respond as expected to foo.hasOwnProperty, so we do a special check
function hasEmberDataProperty(target: any, key: string, options: Options): Boolean {
let fields: Map<string, any> | null = options.safeGet(target, 'constructor.fields');

return fields instanceof Map && fields.has(key);
}

// Protects from prototype poisoning and unexpected merging up the prototype chain.
function propertyIsUnsafe(target: any, key: string): Boolean {
// Special case for ember data model attributes.
if(target.constructor && target.constructor.attributes && target.constructor.attributes.has(key)) {
function propertyIsUnsafe(target: any, key: string, options: Options): Boolean {
if(hasEmberDataProperty(target, key, options)) {
return false;
}

Expand Down Expand Up @@ -83,7 +89,7 @@ function buildPathToValue(source: any, options: Options, kv: Record<string, any>
function mergeTargetAndSource(target: any, source: any, options: Options): any {
getKeys(source).forEach(key => {
// proto poisoning. So can set by nested key path 'person.name'
if (propertyIsUnsafe(target, key)) {
if (propertyIsUnsafe(target, key, options)) {
// if safeSet, we will find keys leading up to value and set
if (options.safeSet) {
const kv: Record<string, any> = buildPathToValue(source, options, {}, []);
Expand Down
4 changes: 4 additions & 0 deletions tests/dummy/app/models/profile.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import DS from 'ember-data';
import attr from 'ember-data/attr';
import { belongsTo } from 'ember-data/relationships';


export default DS.Model.extend({
firstName: attr('string', { defaultValue: 'Bob' }),
lastName: attr('string', { defaultValue: 'Ross' }),

pet: belongsTo('dog'),
});
2 changes: 2 additions & 0 deletions tests/integration/main-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,12 @@ module('Integration | main', function(hooks) {
assert.ok(true, "user save was called");
};
let profile = this.store.createRecord("profile", { save });
let pet = this.store.createRecord('dog')
let profileChangeset = new Changeset(profile);

profileChangeset.set("firstName", "bo");
profileChangeset.set("lastName", "jackson");
profileChangeset.set('pet', pet)

profileChangeset.save();
});
Expand Down

0 comments on commit f2aa827

Please sign in to comment.