SeyZ / jsonapi-serializer

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

Define relationship resource type in serialization options #139

Open adrien-k opened 7 years ago

adrien-k commented 7 years ago

For example I have the following blog post with an author, and I want it serialized as a resource of type posts, with an included resource of type users:

{
  id: '12'
  text: 'Check this out!',
  author: {
    id: '42',
    fullname: 'Foo Bar'
  }
}

The only options I've found so far is to add a customType: 'users' attribute to my author data and to use typeForAttribute: (attribute, data) => data.customType || attribute option.

But when I already know that all my authors are users, is there a solution to statically tell that to the serializer? Otherwise would it be conceivable to define the relationship type with something like this:

var UserSerializer = new JSONAPISerializer('posts', {
  attributes: ['author', 'text'],
  author: {
    ref: 'id',
    type: 'users'  // <-- new option
  }
});

What do you think ?

dhautotlf commented 7 years ago

I need exactly the same. Have you find a way ?

adrien-k commented 7 years ago

@dhautotlf nothing really proper, I used typeForAttribute option to override the type if the relation - found by its name...which won't work when relations of different types have the same name - had a specific type.

ex (completing my previous example):

// Somehow construct this from your relation structure:
const typesForRelations = {author: 'users'};

// Then, in your serializer options:
typeForAttribute: (attribute, resource) => typesForRelations[attribute] || attribute
adrien-k commented 7 years ago

@SeyZ any thoughts ? I could work a quick PR for this.

dhautotlf commented 7 years ago

@adrien-k thanks, I'm lucky that I already have the type defined in my relationship. I can easily serialise it with the typeForAttribute. The inconvenient is I need to import inflector to pluralize the type since option pluralizeType is ignored. A type option would be more than welcome 😄

olosegres commented 7 years ago

@adrien-k @dhautotlf If I understood the promlem, you want to define type of each relation in the data you pass to the serializer, right? If so, checkout jsona, it does exactly what you want :)

yogaraja2 commented 3 years ago

@dhautotlf nothing really proper, I used typeForAttribute option to override the type if the relation - found by its name...which won't work when relations of different types have the same name - had a specific type.

ex (completing my previous example):

// Somehow construct this from your relation structure:
const typesForRelations = {author: 'users'};

// Then, in your serializer options:
typeForAttribute: (attribute, resource) => typesForRelations[attribute] || attribute

Thanks It's very helpful