Last active
August 21, 2017 03:11
-
-
Save ccnokes/2edf1b25960f451d2af7de79e5b28b34 to your computer and use it in GitHub Desktop.
Use a custom cache class in angularJS $http
This file contains 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
// 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