SeyZ / jsonapi-serializer

A Node.js framework agnostic library for (de)serializing your data to JSON API
MIT License
735 stars 196 forks source link

Allow meta for each included resource object #143

Open williamfeng91 opened 7 years ago

williamfeng91 commented 7 years ago

First of all, thanks for adding the option dataMeta!

However that does not work with included resource objects. From my understanding, the spec doesn't restrict us from putting meta in each included resource object which is what I need.

For example I would like to do the following:

var dataSet = [{
  id: '54735750e16638ba1eee59cb',
  firstName: 'Sandro',
  lastName: 'Munda',
  books: [{
    id: '52735730e16632ba1eee62dd',
    title: 'Tesla, SpaceX, and the Quest for a Fantastic Future',
    isbn: '978-0062301239',
    editions: [
      { number: 1 },
      { number: 2 }
    ]
  }, {
    id: '52735780e16610ba1eee15cd',
    title: 'Steve Jobs',
    isbn: '978-1451648546',
    editions: [
      { number: 2000 },
      { number: 2010 },
      { number: 2017 }
    ]
  }]
}, {
  id: '5490143e69e49d0c8f9fc6bc',
  firstName: 'Lawrence',
  lastName: 'Bennett',
  books: [{
    id: '52735718e16610ba1eee15cd',
    title: 'Zero to One: Notes on Startups, or How to Build the Future',
    isbn: '978-0804139298',
    editions: [
      { number: 1 }
    ]
  }]
}];

var json = new JSONAPISerializer('users', {
  attributes: ['firstName', 'lastName', 'books'],
  books: {
    ref: 'id',
    attributes: ['title', 'isbn'],
    dataMeta: {
      editionCount: function (record, current) {
        return current.editions.length;
      }
    }
  }
}).serialize(dataSet);

expect(json.included[0].meta.editionCount).equal(2);
expect(json.included[1].meta.editionCount).equal(3);
expect(json.included[2].meta.editionCount).equal(1);

I'm happy to submit a pull request if you agree with this.

xaviertholot commented 6 years ago

Hello,

I have encountered the same issue and fixed in on my fork. Here is a PR : https://github.com/SeyZ/jsonapi-serializer/pull/160

@SeyZ I don't know if it works for all purposes but I tried it on my project and it works for my use cases.

Would appreciate very much to have this in a next release ;-)

antokara commented 5 years ago

I believe the same applies to links...