'use strict'

import readCache from './read-cache'
import serialize from './serialize'

function cache (config = {}) {
  if (!config.store) {
    throw new Error('Cache middleware need to be provided a store.')
  }

  const store = config.store
  const key = config.key || cache.key

  config.readCache = config.readCache || readCache
  config.serialize = config.serialize || serialize

  if (config.log !== false) {
    config.log = typeof config.log === 'function' ? config.log : console.log.bind(console)
  }

  return (req, next, service) => {
    if (service) {
      const useCache = !service.use || (service.use && (service.use.cache !== false))

      if (!useCache) {
        return null
      }
    }

    // do not cache request with query
    if (req.url.match(/\?.*$/)) {
      return null
    }

    const uuid = key(req)

    const f = () => {
      return next()
        .then(res => {
          return store.setItem(uuid, config.serialize(req, res))
        })
    }

    return store.getItem(uuid).then(value => {
      return config.readCache(req, config.log)(value)
        .catch(err => { // eslint-disable-line handle-callback-err
          f()
        })
    })
  }
}

cache.readCache = readCache
cache.serialize = serialize

cache.key = function (req) {
  return req.url
}

export default cache

@@ -830,16 +830,164 @@
 y(req)%0A%0A
+    // clear cache if method different from GET%0A    if (req.method.toLowerCase() !== 'get') %7B%0A      store.removeItem(uuid)%0A      return null%0A    %7D%0A%0A
     cons

delete cache for any non get request