jsonapi-serializer
jsonapi-serializer copied to clipboard
Define relationship resource type in serialization options
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 ?
I need exactly the same. Have you find a way ?
@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
@SeyZ any thoughts ? I could work a quick PR for this.
@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 😄
@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 :)
@dhautotlf nothing really proper, I used
typeForAttributeoption 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