Created
November 28, 2019 07:45
-
-
Save multimeric/9a76026da1295fbb864754abfc87ed65 to your computer and use it in GitHub Desktop.
Hacky solution for https://github.com/SeyZ/jsonapi-serializer/issues/58
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Serializer, Deserializer } from 'jsonapi-serializer'; | |
return new Deserializer(relationshipProxy).deserialize(response.data); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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