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

Allow meta for each included resource object

Open williamfeng91 opened this issue 8 years ago • 2 comments

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.

williamfeng91 avatar Jun 01 '17 07:06 williamfeng91

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 ;-)

xaviertholot avatar Oct 27 '17 12:10 xaviertholot

I believe the same applies to links...

antokara avatar Nov 12 '18 16:11 antokara