Skip to content

Instantly share code, notes, and snippets.

@davidchase
Created April 8, 2016 14:19
Show Gist options
  • Save davidchase/f1c8e03d06e38370bb0a33fd8ee0ce5d to your computer and use it in GitHub Desktop.
Save davidchase/f1c8e03d06e38370bb0a33fd8ee0ce5d to your computer and use it in GitHub Desktop.
local forage
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
import localforage from 'localforage';
import {resolve} from 'creed';
import {fromPromise, just, fromEvent} from 'most';
import {log, throttle} from './utils';
import {set, get, remove} from 'tiny-cookie';
const cacheStore = localforage.createInstance({
name: 'cachebox'
});
const expiration = get('expired') ? get('expired') : set('expired', Date.now() + 10e4);
const isExpired = function() {
if (get('expired') - Date.now() < 0) {
remove('expired');
return true;
}
return false;
}
const fetchUrl = throttle(() => fetch('http://reqres.in/api/users?page=2').then(resp => resp.json()));
const checkExpiration = (expired = false) => expired ? cacheStore.removeItem('cachee') : resolve(null);
const getCache = function() {
return checkExpiration(isExpired())
.then(function() {
return cacheStore.getItem('cachee')
})
.then(function(cache) {
return !cache ? fetchUrl().then(data => cacheStore.setItem('cachee', data)) : resolve(cache);
})
.then(function(stuff) {
return stuff;
});
};
getCache().then(log);
getCache().then(log);
getCache().then(log);
const throttle = function throttle(fn) {
let called = false;
let result;
return function() {
if (called) {
return result;
}
called = true;
result = fn.apply(this, arguments);
return result;
}
};
const log = console.log.bind(console);
export {throttle, log};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment