Skip to content

Commit 075a258

Browse files
Vincent MoliniéSeyZ
authored andcommitted
fix(serialize): fix keys serialization of nested attributes
1 parent b0315e9 commit 075a258

File tree

2 files changed

+41
-10
lines changed

2 files changed

+41
-10
lines changed

lib/serializer-utils.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ module.exports = function (collectionName, record, payload, opts) {
239239
var embeds = [];
240240
var attributes = [];
241241

242+
var ret = {};
242243
if (opts && opts.attributes) {
243244
embeds = opts.attributes.filter(function (attr) {
244245
return opts[attr];
@@ -247,18 +248,17 @@ module.exports = function (collectionName, record, payload, opts) {
247248
attributes = opts.attributes.filter(function (attr) {
248249
return !opts[attr];
249250
});
250-
} else {
251-
attributes = _keys(dest);
252-
}
253251

254-
var ret = {};
255-
if (attributes) { ret.attributes = pick(dest, attributes); }
252+
if (attributes) { ret.attributes = pick(dest, attributes); }
256253

257-
embeds.forEach(function (embed) {
258-
if (isComplexType(dest[embed])) {
259-
that.serialize(ret, dest, embed, opts[embed]);
260-
}
261-
});
254+
embeds.forEach(function (embed) {
255+
if (isComplexType(dest[embed])) {
256+
that.serialize(ret, dest, embed, opts[embed]);
257+
}
258+
});
259+
} else {
260+
ret.attributes = dest;
261+
}
262262

263263
return ret.attributes;
264264
};

test/serializer.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,37 @@ describe('Options', function () {
464464

465465
done(null, json);
466466
});
467+
468+
it('should not change keys of nested object if not specified', function (done) {
469+
var dataSet = {
470+
id: '1',
471+
nestedTest: {
472+
dontChange: 1
473+
},
474+
nestedArrayTest: [{
475+
dontChange: 1
476+
}],
477+
};
478+
479+
var json = new JSONAPISerializer('user', {
480+
attributes: ['nestedTest', 'nestedArrayTest'],
481+
keyForAttribute: 'underscore_case',
482+
}).serialize(dataSet);
483+
484+
expect(json.data.type).equal('users');
485+
expect(json.data).to.have.property('attributes').that.is
486+
.an('object')
487+
.eql({
488+
'nested_test': {
489+
dontChange: 1
490+
},
491+
'nested_array_test': [{
492+
dontChange: 1
493+
}],
494+
});
495+
496+
done(null, json);
497+
});
467498
});
468499

469500
describe('keyForAttribute case strings', function () {

0 commit comments

Comments
 (0)