Skip to content

Instantly share code, notes, and snippets.

@soutar
Last active August 29, 2015 14:22
Show Gist options
  • Save soutar/b54162ec321c343cd4ab to your computer and use it in GitHub Desktop.
Save soutar/b54162ec321c343cd4ab to your computer and use it in GitHub Desktop.
API response caching with ObjectCache in Javascript
import ObjectCache from '../ObjectCache';
import ObjectStoreDriver from '../drivers/ObjectStoreDriver';
let cache = new ObjectCache(ObjectStoreDriver);
let requests = 0;
let cacheHits = 0;
function getData () {
let cached = cache.get('apidata');
return (cached)
? Promise.resolve(cached).then((obj) => { cacheHits++; return obj; })
: fetch('http://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((obj) => {
requests++;
cache.set('apidata', obj, [10, 'seconds']);
return obj;
});
}
export default function APICacheDemo () {
console.log('This demo makes an api call to JSONPlaceholder and caches the response for 10 seconds. Any invokations of the getData() function that occur before the cache has expired will be given the data from memory, avoiding extra network requests.');
console.log('Endpoint: http://jsonplaceholder.typicode.com/posts/1');
let count = 0;
setInterval(function () {
count++;
getData().then((obj) => {
console.log(`Request #${count}`, '|',`API hits: ${requests}`, '|', `Cache hits: ${cacheHits}`);
console.log(obj);
});
}, 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment