Skip to content

Instantly share code, notes, and snippets.

@tychay

tychay/config.js

Forked from pywebdesign/config.js
Last active Mar 1, 2017
Embed
What would you like to do?
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
You can’t perform that action at this time.