Last active
December 30, 2015 20:59
-
-
Save subnetmarco/7883866 to your computer and use it in GitHub Desktop.
Consuming the DB api
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
| var unirest = require('unirest'); | |
| function get(url, callback) { | |
| unirest.get(url).end(function (response) { | |
| var result, entity = response.body; | |
| if (entity.data) { | |
| result =[]; | |
| for(var t=0;t<entity.data.length;t++) { | |
| result.push(_prepare(entity.data[t])); | |
| } | |
| } else { | |
| result = _prepare(entity); | |
| } | |
| callback(result); | |
| }); | |
| } | |
| function _prepare(entity) { | |
| entity._cache = {}; | |
| if (entity._links) { | |
| var refNames = Object.keys(entity._links) | |
| var length = refNames.length; | |
| var parent = null; | |
| for(var i=0;i<length;i++) { | |
| var refName = refNames[i]; | |
| var link = entity._links[refName]; | |
| entity[refName] = (function (link, refName) { | |
| return function(callback, reload) { | |
| if (!reload && entity._cache[refName]) { | |
| callback(entity._cache[refName]); | |
| } else { | |
| get(link.href, function(response) { | |
| entity._cache[refName] = response; | |
| callback(response); | |
| }); | |
| } | |
| } | |
| })(link, refName); | |
| if (link.parent) entity.parent = entity[refName]; | |
| } | |
| delete entity._links; | |
| } | |
| return entity; | |
| } | |
| get("http://192.168.50.5:8080/mashape-apis-database-server/v1/accounts/mashaper", function(user) { | |
| user.profile(function(profile) { | |
| }); // LAZY LOADED | |
| user.profile(function(profile) { | |
| }); // THIS IS RETRIEVED FROM CACHE | |
| user.profile(function(profile) { | |
| profile.parent(function(parent) { | |
| // THE PARENT IS USER | |
| }); | |
| }, true); // FORCE RELOAD, RE-MAKES THE REQUEST | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment