jsonapi-serializer icon indicating copy to clipboard operation
jsonapi-serializer copied to clipboard

Fix serialization of id property

Open tomislavherman opened this issue 6 years ago • 1 comments

Latest version (3.5.6 on npm) introduced change in output when input id is integer:

  • id property is not converted to string type any more, but in 3.5.5 it was converted. JSON API specification requires that id is string: http://jsonapi.org/format/#document-resource-object-identification
  • if input id property is equal to 0, it is missing in output

Example:

var data = [
  { id: 0, firstName: 'Sandro', lastName: 'Munda' },
  { id: 1, firstName: 'John', lastName: 'Doe' }
];

var JSONAPISerializer = require('jsonapi-serializer').Serializer;

var UserSerializer = new JSONAPISerializer('users', {
  attributes: ['firstName', 'lastName']
});

var users = UserSerializer.serialize(data);

Current output:

{
  "data": [
    {
      "type": "users",
      "id": 1,
      "attributes": {
        "first-name": "John",
        "last-name": "Doe"
      }
    }
  ]
}

Output with this PR:

{
  "data": [
    {
      "type": "users",
      "id": "0",
      "attributes": {
        "first-name": "Sandro",
        "last-name": "Munda"
      }
    }, {
      "type": "users",
      "id": "1",
      "attributes": {
        "first-name": "John",
        "last-name": "Doe"
      }
    }
  ]
}

tomislavherman avatar Mar 05 '18 21:03 tomislavherman

Anyway to get this merged in? We're running into this now with any id that is the value 0. It's affecting version 3.4.3 and not just the latest.

---- Edit

Actually this does not appear to fix all the issues with 0 id models. While I'm pretty sure we have this issue there are other issues with having an id of 0 when using included relationships (any object with an id of 0 won't be included).

Looking briefly through the code it looks like there are lots of places where if checks are done using truthy statements which would cause problems anytime an id is 0. Probably need to go through and find all those locations and convert to using _isNil like in this PR.

Thanks!

sarus avatar Oct 02 '18 02:10 sarus