From 404b99699a310fa5305cb68606831943d487981d Mon Sep 17 00:00:00 2001 From: Mehdi Lahlou Date: Tue, 26 Oct 2021 17:16:16 +0200 Subject: [PATCH] fix: remove undefined `id` on deserialized data when the input has no `id` (#131) * test: add a failing test on the presence of an `id` property on deserialized data when the input has no `id` * fix: remove `id: undefined` from deserialized output when the input data had no `id` --- lib/JSONAPISerializer.js | 4 +++- test/unit/JSONAPISerializer.test.js | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/JSONAPISerializer.js b/lib/JSONAPISerializer.js index ee96100..b5994f5 100644 --- a/lib/JSONAPISerializer.js +++ b/lib/JSONAPISerializer.js @@ -385,7 +385,9 @@ module.exports = class JSONAPISerializer { const options = this.schemas[type][schema]; let deserializedData = {}; - deserializedData[options.id] = data.id || undefined; + if (data.id !== undefined) { + deserializedData[options.id] = data.id; + } if (data.attributes && options.whitelistOnDeserialize.length) { data.attributes = pick(data.attributes, options.whitelistOnDeserialize); diff --git a/test/unit/JSONAPISerializer.test.js b/test/unit/JSONAPISerializer.test.js index a900215..7e47746 100644 --- a/test/unit/JSONAPISerializer.test.js +++ b/test/unit/JSONAPISerializer.test.js @@ -2961,6 +2961,22 @@ describe('JSONAPISerializer', function() { done(); }); + + it("should return deserialized data without 'id' for a single data without 'id'", function(done) { + const singleData = { + data: { + type: 'article', + attributes: { + title: 'JSON API paints my bikeshed!', + } + } + }; + const deserializedData = Serializer.deserialize(typeOption, singleData); + + expect(deserializedData).to.not.have.property('id'); + expect(deserializedData).to.have.property('title').to.eql('JSON API paints my bikeshed!'); + done(); + }); }); describe('serializeError', function() {