Last active
August 29, 2015 14:22
-
-
Save teone/72668551eaad31ff5eae to your computer and use it in GitHub Desktop.
Example, how to cache a request with loopback
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
| '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