'use strict'

import readCache from './read-cache'

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

  const store = config.store
  const cache = config.cache

  if (!config.cache || typeof config.cache !== 'function') {
    throw new Error('Cache middleware need a cache function.')
  }

  const read = config.readCache || readCache

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

    if (!useCache) {
      return next()
    }

    return store.getItem(req.url)
      .then(read(req))
      .catch((err) => {
        const promise = next()

        return promise
      })
  }
}

cache.readCache = readCache

export default cache

@@ -210,21 +210,19 @@
   const 
-cache
+key
  = confi
@@ -227,143 +227,24 @@
 fig.
-cache%0A%0A  if (!config.cache %7C%7C typeof config.cache !== 'function') %7B%0A    throw new Error('Cache middleware need a cache function.')%0A  %7D%0A
+key %7C%7C cache.key
 %0A  c
@@ -483,15 +483,16 @@
 tem(
-req.url
+key(req)
 )%0A  
@@ -607,16 +607,16 @@
 %0A  %7D%0A%7D%0A%0A
-
 cache.re
@@ -634,16 +634,64 @@
 eadCache
+%0Acache.key = function (req) %7B%0A  return req.url%0A%7D
 %0A%0Aexport

add overridable function to define the cache key