// @flow

import type { Cache } from '../types/Cache'

const DEFAULT_MAX_AGE = 15 * 60 * 1000 // 15 minutes
const STORE = 'api-cacher'

class Cacher {
  load(options: {
    key: string,
    maxAge?: ?number,
  }): ?any {
    let { key, maxAge } = options
    let storage: Cache = JSON.parse(localStorage.getItem(STORE) || '{}')
    let item = storage[key]
    if (!item) {
      return null
    }
    let createdAt = new Date(item.createdAt).getTime()
    let actualMaxAge = (maxAge || DEFAULT_MAX_AGE)
    if (new Date().getTime() - createdAt > actualMaxAge) {
      delete storage[key]
      localStorage.setItem(STORE, JSON.stringify(storage))
      return null
    }
    console.log(`%cFrom cache ${key}`, 'color: #777A8B', item.data)
    return item.data
  }

  save(options: {
    key: string,
    data: any,
  }) {
    let { key, data } = options
    let storage: Cache = JSON.parse(localStorage.getItem(STORE) || '{}')
    storage[key] = {
      data,
      createdAt: new Date().toISOString(),
    }
    localStorage.setItem(STORE, JSON.stringify(storage))
  }
}

export default new Cacher()

@@ -48,16 +48,39 @@
 Cache'%0A%0A
+const MAX_ITEMS = 100%0A%0A
 const DE
@@ -939,24 +939,320 @@
 E) %7C%7C '%7B%7D')%0A
+    let keys = Object.keys(storage)%0A    if (keys.length %3E= MAX_ITEMS + 10) %7B%0A      keys.sort((a, b) =%3E new Date(storage%5Ba%5D.createdAt).getTime() - new Date(storage%5Bb%5D.createdAt).getTime())%0A      for (let i = 0; i %3C= keys.length - MAX_ITEMS; i += 1) %7B%0A        delete storage%5Bkeys%5Bi%5D%5D%0A      %7D%0A    %7D%0A
     storage%5B

Set a maximum cached API calls requests to 100