scoutforpets / jsonapi-mapper

JSON API-Compliant Serialization for your Node ORM
The Unlicense
42 stars 24 forks source link

Bad template generation for related collections #60

Closed jcao02 closed 8 years ago

jcao02 commented 8 years ago

There's a problem in the getSample function (here) where you're attempting to merge multiple Bookshelf objects using lodash merge function.

More specifically: If you try to merge two objects with a common key containing a Bookshelf Collection, for some reason lodash merge does not recur in the collections but it compares them as a whole keeping the last one as the final value. This can result in a template error if the last collection is empty or if it contains only models that lack any of the attributes you wish to serialize.

If you need to reproduce the error:

let obj = bookshelf.Model.forge({ a: 1 });
let objs = bookshelf.Collection.forge([obj]);
let objs2 = bookshelf.Collection.forge([]);

let x = [
  {
    relations: {
      relName: objs
    }
  },
  {
    relations: {
      relName: objs2
    }
  }
];

console.log(JSON.stringify(_.reduce(x, _.merge, {})));