Skip to content

Instantly share code, notes, and snippets.

@tychay
Forked from pywebdesign/config.js
Last active March 1, 2017 19:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tychay/7f535e9505da16347d74 to your computer and use it in GitHub Desktop.
Save tychay/7f535e9505da16347d74 to your computer and use it in GitHub Desktop.
Restangular adapter to expand compound documents from jsonapi.org
// This variation just injects the extracted data right into the relationships and also stores things in
// ._meta and ._included instead of just .included
// it (like restangular) requires either lodash or underscorejs
.config(function(RestangularProvider) {
// add a response interceptor
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData = data.data;
function _apply(elem, fct) {
if ( elem === undefined ) { return; }
if ( elem.type !== undefined ) {
fct(elem);
} else {
_.forEach(elem, function(el) {
_apply(el, fct);
});
}
}
// TODO: restangularize all the included stuff (would have to be moved outside of provider to work)
// replace relationships with included data
_apply(data.data, function(elem) {
_apply(elem.relationships, function(rel) {
var include_obj = _.find(data.included, function(included) {
return ( ( included.type == rel.type ) && ( included.id == rel.id ) );
});
if ( include_obj ) {
_.merge(rel,include_obj);
}
});
});
// save a copy of included and metadata
extractedData._meta = data.meta;
extractedData._included = data.included;
return extractedData;
});
});
//simply call the relationship object and bam!
seller.relationships.user.data.attributes.name
// Note that the relationships are not restangularized properly because it is in the provider above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment