Skip to content

Commit

Permalink
Dont serialize new belongsTo records (#5317)
Browse files Browse the repository at this point in the history
* Dont serialize new belongsTo records that do not have an ID

* Add a test for nulling out a belognsTo relationship
  • Loading branch information
ryanto authored and bmac committed Jan 10, 2018
1 parent 7c6448d commit 25ebee6
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
3 changes: 2 additions & 1 deletion addon/serializers/json-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -555,8 +555,9 @@ const JSONAPISerializer = JSONSerializer.extend({

if (this._canSerialize(key)) {
let belongsTo = snapshot.belongsTo(key);
if (belongsTo !== undefined) {
let belongsToIsNotNew = belongsTo && belongsTo.record && !belongsTo.record.get('isNew');

if (belongsTo === null || belongsToIsNotNew) {
json.relationships = json.relationships || {};

let payloadKey = this._getMappedKey(key, snapshot.type);
Expand Down
72 changes: 72 additions & 0 deletions tests/integration/serializers/json-api-serializer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,78 @@ testInDebug('Warns when defining extractMeta()', function(assert) {
}, /You've defined 'extractMeta' in/);
});

test('a belongsTo relationship that is not set will not be in the relationships key', function(assert) {
run(function() {
serializer.pushPayload(store, {
data: {
type: 'handles',
id: 1
}
});

let handle = store.peekRecord('handle', 1);

let serialized = handle.serialize({ includeId: true });
assert.deepEqual(serialized, {
data: {
type: 'handles',
id: '1'
}
});
});
});

test('a belongsTo relationship that is set to null will show as null in the relationships key', function(assert) {
run(function() {
serializer.pushPayload(store, {
data: {
type: 'handles',
id: 1
}
});

let handle = store.peekRecord('handle', 1);
handle.set('user', null);

let serialized = handle.serialize({ includeId: true });
assert.deepEqual(serialized, {
data: {
type: 'handles',
id: '1',
relationships: {
user: {
data: null
}
}
}
});
});
});

test('a belongsTo relationship set to a new record will not show in the relationships key', function(assert) {
run(function() {
serializer.pushPayload(store, {
data: {
type: 'handles',
id: 1
}
});

let handle = store.peekRecord('handle', 1);

let user = store.createRecord('user');
handle.set('user', user);

let serialized = handle.serialize({ includeId: true });
assert.deepEqual(serialized, {
data: {
type: 'handles',
id: '1'
}
});
});
});

testInDebug('JSON warns when combined with EmbeddedRecordsMixin', function(assert) {
assert.expectWarning(function() {
DS.JSONAPISerializer.extend(DS.EmbeddedRecordsMixin).create();
Expand Down

0 comments on commit 25ebee6

Please sign in to comment.