diff --git a/lib/serializer-utils.js b/lib/serializer-utils.js index ea7a47d..05f1c26 100644 --- a/lib/serializer-utils.js +++ b/lib/serializer-utils.js @@ -41,10 +41,10 @@ module.exports = function (collectionName, record, payload, opts) { return item.map(function (val) { return String(val); }); - } else { + } else if (item) { return String(item); } - } else { + } else if (item && item[opts.ref]){ return String(item[opts.ref]); } } @@ -187,13 +187,11 @@ module.exports = function (collectionName, record, payload, opts) { if (opts.includedLinks) { included.links = getLinks(dest, opts.includedLinks); } - // only add to included array if the resource is defined - if(id !== 'undefined') { - pushToIncluded(payload, included); - } + + if (typeof id !== 'undefined') { pushToIncluded(payload, included); } } - return id !== 'undefined' ? { type: type, id: id } : null; + return typeof id !== 'undefined' ? { type: type, id: id } : null; }; this.serializeNested = function (dest, current, attribute, opts) { diff --git a/test/serializer.js b/test/serializer.js index dabe24c..b8a2543 100644 --- a/test/serializer.js +++ b/test/serializer.js @@ -648,6 +648,28 @@ describe('JSON API Serializer', function () { }); }); + describe('Null relationship', function () { + it('should serialize the relationship as { data: null }', function (done) { + var dataSet = { + id: '54735750e16638ba1eee59cb', + firstName: 'Sandro', + lastName: 'Munda', + address: null, + }; + + var json = new JSONAPISerializer('user', { + attributes: ['firstName', 'lastName', 'address'], + address: { + ref: 'id', + included: false + } + }).serialize(dataSet); + + expect(json.data.relationships.address).eql({ data: null }); + done(null, json); + }); + }); + describe('Nested of nested document', function () { it('should be serialized', function (done) { var dataSet = { @@ -1910,5 +1932,4 @@ describe('JSON API Serializer', function () { done(null, json); }); }); - });