jsonapi-serializer
jsonapi-serializer copied to clipboard
Options for global `valueForRelationship` and `valueForIdWhenNotIncluded`
I'm currently working on tests and implementation for this, but I'm on my way to work and switching workstations so need a reminder of the goal...
Currently each individual relationship has to be given a valueForRelationship.
The idea is that if a relationship valueForRelationship is not found fallback to a configurable valueForRelationship that lies on the root of the options.
Also, right now if there is no included data, then ids are not deserialized
ids are not deserializedconst JsonApiSerializer = require("jsonapi-serializer")
var dataSet = {
data: {
type: 'users',
id: '54735750e16638ba1eee59cb',
attributes: {
'first-name': 'Sandro',
'last-name': 'Munda'
},
relationships: {
address: {
data: {
id: '2e593a7f2c3f2e5fc0b6ea1d4f03a2a3',
type: 'address'
}
}
}
}
};
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
new JSONAPIDeserializer().deserialize(dataSet, function (err, users) {
console.log(users.address) // undefined
});
The idea is to allow this to be customized using a method valueForIdNotIncluded.
This means that the above behavior remains, but users can add valueForIdWhenNotIncluded to create:
const JsonApiSerializer = require("jsonapi-serializer")
var dataSet = {
data: {
type: 'users',
id: '54735750e16638ba1eee59cb',
attributes: {
'first-name': 'Sandro',
'last-name': 'Munda'
},
relationships: {
address: {
data: {
id: '2e593a7f2c3f2e5fc0b6ea1d4f03a2a3',
type: 'address'
}
}
}
}
};
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
new JSONAPIDeserializer({
valueForIdNotIncluded(data) {
return data.id;
}
}).deserialize(dataSet, function (err, users) {
console.log(users.address) // "2e593a7f2c3f2e5fc0b6ea1d4f03a2a3"
});
new JSONAPIDeserializer({
valueForIdNotIncluded(data) {
return data.id + ':' + data.type;
}
}).deserialize(dataSet, function (err, users) {
console.log(users.address) // "2e593a7f2c3f2e5fc0b6ea1d4f03a2a3:address"
});
I could really do with this in our project. I need the id of relationships on the deserialized object and at the moment the only way I can see to do it involves hacking around valueForRelationship with some pretty nasty looping over included items and relationships to see if they're empty and if so then return just the id. @rtablada Did you every find a workaround / solution to this?