Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set undefined attribute values to null if missingIfNull flag is set. Ignore other falsy values. #242

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/serializer-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
}
});
Expand Down Expand Up @@ -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;
}

Expand Down
25 changes: 25 additions & 0 deletions test/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down