From a978cd0f179d5f1eac30c6abd75b1e2bb9b18757 Mon Sep 17 00:00:00 2001 From: hinsenchan Date: Wed, 28 Oct 2020 22:00:10 -0700 Subject: [PATCH] Set undefined attribute values to null if missingIfNull flag is set. Ignore other falsy values. --- lib/serializer-utils.js | 5 +++-- test/serializer.js | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/lib/serializer-utils.js b/lib/serializer-utils.js index c37520e..aae172d 100644 --- a/lib/serializer-utils.js +++ b/lib/serializer-utils.js @@ -12,6 +12,7 @@ var _pickBy = require('lodash/pickBy'); var _keys = require('lodash/keys'); var _each = require('lodash/each'); var _isNil = require('lodash/isNil'); +var _isUndefined = require("lodash/isUndefined"); var Inflector = require('./inflector'); module.exports = function (collectionName, record, payload, opts) { @@ -198,7 +199,7 @@ module.exports = function (collectionName, record, payload, opts) { if (opts.attributes) { if (dest) { opts.attributes.forEach(function (attr) { - if (opts[attr] && !dest[attr] && opts[attr].nullIfMissing) { + if (opts[attr] && _isUndefined(dest[attr]) && opts[attr].nullIfMissing) { dest[attr] = null; } }); @@ -292,7 +293,7 @@ module.exports = function (collectionName, record, payload, opts) { _each(opts.attributes, function (attribute) { var splittedAttributes = attribute.split(':'); - if (opts[attribute] && !record[attribute] && opts[attribute].nullIfMissing) { + if (opts[attribute] && _isUndefined(record[attribute]) && opts[attribute].nullIfMissing) { record[attribute] = null; } diff --git a/test/serializer.js b/test/serializer.js index 22ed0e4..5691e87 100644 --- a/test/serializer.js +++ b/test/serializer.js @@ -2260,6 +2260,31 @@ describe('JSON API Serializer', function () { done(null, json); }); + it('should not set the attr to null with nullIfMissing option', function (done) { + var dataSet = [{ + id: '54735750e16638ba1eee59cb', + firstName: 'Sandro', + lastName: 'Munda', + isActive: false, + count: 0 + }]; + + var json = new JSONAPISerializer('users', { + attributes: ['firstName', 'lastName', 'isActive', 'count'], + isActive: { + nullIfMissing: true + }, + count: { + nullIfMissing: true + } + }).serialize(dataSet); + + // jshint expr: true + expect(json.data[0].attributes['is-active']).to.be.false; + expect(json.data[0].attributes.count).eql(0); + done(null, json); + }); + it('should add the relationship with nullIfMissing option', function (done) { var dataSet = [{ id: '54735750e16638ba1eee59cb',