Cacher.js 1.1 KB

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