Skip to content

Instantly share code, notes, and snippets.

@teone
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save teone/72668551eaad31ff5eae to your computer and use it in GitHub Desktop.

Select an option

Save teone/72668551eaad31ff5eae to your computer and use it in GitHub Desktop.
Example, how to cache a request with loopback
'use strict';
angular.module('lbServices')
.config(function($provide) {
// store if a request is being processed
var pending = false;
$provide.decorator('Access_credential', function($delegate, $q, $cacheFactory){
// store the original method
let getCurrent = $delegate.getCurrent;
// create a cache Object
let userCache = $cacheFactory('userCache');
// override the getCurrent method
$delegate.getCurrent = function(){
// create a promise
let deferred = $q.defer();
// if the user is cached
var currentUser = userCache.get('currentUser');
if(currentUser !== undefined){
deferred.resolve(currentUser);
}
// if the user is not cached
else if(!pending){
pending = true;
getCurrent().$promise
.then(function(user){
userCache.put('currentUser', user);
pending = false;
deferred.resolve(user);
})
.catch(deferred.reject);
}
return deferred.promise;
};
// provide a method to clear the cache
$delegate.prototype.bustCache = function() {
userCache.remove('currentUser');
};
return $delegate;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment