Cacher.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // @flow
  2. import type { Cache } from '../types/Cache'
  3. const MAX_ITEMS = 100
  4. const DEFAULT_MAX_AGE = 30 * 60 * 1000 // 30 minutes
  5. const STORE = 'api-cacher'
  6. class Cacher {
  7. load(options: {
  8. key: string,
  9. maxAge?: ?number,
  10. }): ?any {
  11. let { key, maxAge } = options
  12. let storage: Cache = JSON.parse(localStorage.getItem(STORE) || '{}')
  13. let item = storage[key]
  14. if (!item) {
  15. return null
  16. }
  17. let createdAt = new Date(item.createdAt).getTime()
  18. let actualMaxAge = (maxAge || DEFAULT_MAX_AGE)
  19. if (new Date().getTime() - createdAt > actualMaxAge) {
  20. delete storage[key]
  21. localStorage.setItem(STORE, JSON.stringify(storage))
  22. return null
  23. }
  24. console.log(`%cFrom cache ${key}`, 'color: #777A8B', item.data)
  25. return item.data
  26. }
  27. save(options: {
  28. key: string,
  29. data: any,
  30. }) {
  31. let { key, data } = options
  32. let storage: Cache = JSON.parse(localStorage.getItem(STORE) || '{}')
  33. let keys = Object.keys(storage)
  34. if (keys.length >= MAX_ITEMS + 10) {
  35. keys.sort((a, b) => new Date(storage[a].createdAt).getTime() - new Date(storage[b].createdAt).getTime())
  36. for (let i = 0; i <= keys.length - MAX_ITEMS; i += 1) {
  37. delete storage[keys[i]]
  38. }
  39. }
  40. storage[key] = {
  41. data,
  42. createdAt: new Date().toISOString(),
  43. }
  44. localStorage.setItem(STORE, JSON.stringify(storage))
  45. }
  46. }
  47. export default new Cacher()