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);
}