Skip to content

Instantly share code, notes, and snippets.

@multimeric
Created November 28, 2019 07:45
Show Gist options
  • Save multimeric/9a76026da1295fbb864754abfc87ed65 to your computer and use it in GitHub Desktop.
Save multimeric/9a76026da1295fbb864754abfc87ed65 to your computer and use it in GitHub Desktop.
import { Serializer, Deserializer } from 'jsonapi-serializer';
return new Deserializer(relationshipProxy).deserialize(response.data);
/**
* This proxy ensures that every relationship is serialized to an object of the form {id: x}, even if that relationship
* doesn't have included data
*/
const specialOpts = [ 'transform', 'keyForAttribute', 'id', 'typeAsAttribute' ];
const relationshipProxy = new Proxy({}, {
has(target, key) {
// Pretend to have all keys except certain ones with special meanings
return !specialOpts.includes(key);
},
get(target, key, receiver) {
if (specialOpts.includes(key)) {
return undefined;
}
return {
valueForRelationship(data, included) {
// If we have actual included data use it, but otherwise just return the id in an object
if (included){
return included;
} else {
return { id: data.id };
}
},
};
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment