Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active August 21, 2017 03:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/2edf1b25960f451d2af7de79e5b28b34 to your computer and use it in GitHub Desktop.
Save ccnokes/2edf1b25960f451d2af7de79e5b28b34 to your computer and use it in GitHub Desktop.
Use a custom cache class in angularJS $http
// This class implements the same interface that the cache created by $cacheFactory does
// See https://github.com/angular/angular.js/blob/master/src/ng/cacheFactory.js#L142
// This cache evicts an entry once it's expired (which we define as 5 seconds).
class ExpirationCache {
constructor(timeout = 5000) {
this.store = new Map();
this.timeout = timeout;
}
get(key) {
this.store.has(key) ? console.log(`cache hit`) : console.log(`cache miss`);
return this.store.get(key);
}
put(key, val) {
this.store.set(key, val);
// remove it once it's expired
setTimeout(() => {
console.log(`removing expired key ${key}`);
this.remove(key);
}, this.timeout);
}
remove(key) {
this.store.delete(key);
}
removeAll() {
this.store = new Map();
}
delete() {
//no op here because this is standalone, not a part of $cacheFactory
}
}
// Now implement it....
angular.module('app', [])
.run(function ($http, $cacheFactory) {
// create the instance
const expCache = new ExpirationCache();
function getPokemon(id) {
return $http({
cache: expCache, //the cache prop can be true to use the default, or you can pass one
url: `http://pokeapi.co/api/v2/pokemon/${id}/`,
method: 'GET'
});
}
Promise.all([
getPokemon(1),
getPokemon(1), //this will be a cache hit
getPokemon(2)
]).then(console.log);
// Get pokemon 1 again after 6 seconds. This will be a cache miss because the entry has expired and was evicted.
setTimeout(() => getPokemon(1), 6000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment