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

Define relationship resource type in serialization options

Open adrien-k opened this issue 8 years ago • 6 comments

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 ?

adrien-k avatar May 05 '17 09:05 adrien-k

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

dhautotlf avatar Jun 07 '17 09:06 dhautotlf

@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 avatar Jun 07 '17 10:06 adrien-k

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

adrien-k avatar Jun 07 '17 10:06 adrien-k

@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 😄

dhautotlf avatar Jun 07 '17 12:06 dhautotlf

@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 :)

olosegres avatar Jun 13 '17 19:06 olosegres

@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

yogaraja2 avatar Sep 30 '21 17:09 yogaraja2