Skip to content

Instantly share code, notes, and snippets.

@matthewharwood
Created October 14, 2014 16:11
Show Gist options
  • Save matthewharwood/49371de89f16e12db461 to your computer and use it in GitHub Desktop.
Save matthewharwood/49371de89f16e12db461 to your computer and use it in GitHub Desktop.
Use many controllers to create a cue of requests but only have one successful response store that response. The cue then return cache!
angular.module('giphyApp')
.factory('Gifs', function ($http, $q) {
var Gifs = {};
var cachedPromise = {};
var api = {
base: 'http://api.giphy.com/v1/gifs/search?q=',
auth: '&api_key=dc6zaTOxFJmzC'
};
Gifs.main = {
getGifs: function(request){
//use the request as a unique idenifier (key)
var reqKey = request;
//sets the api url
var apiUrl = api.base + reqKey + api.auth;
//if the promise + unique key is already fullfilled just return that
if(cachedPromise[reqKey]) {
console.log('cached', cachedPromise[reqKey]);
return cachedPromise[reqKey];
}
//GET request via $q and returns response to cachePromise for other requests
cachedPromise[reqKey] = $http.get(apiUrl)
.then(function(result){
//returns response data
return result.data;
}, function(data, status){
return $q.reject('error in teh gifson' + 'data: ' + data + 'status: ' + status);
}).finally( function(){
delete cachedPromise[reqKey];
});
return cachedPromise[reqKey];
}
};
return Gifs;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment