Skip to content

Commit

Permalink
feat(cache): add support for expiration
Browse files Browse the repository at this point in the history
  • Loading branch information
stephanebachelier committed Feb 19, 2016
1 parent 69729a3 commit 9809510
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
7 changes: 4 additions & 3 deletions lib/hydrate.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@ function parseHeader (str) {
}

export default function hydrate (value) {
const xhr = value.body || {}
const headers = parseHeader(value.headers || {})
const data = value.data
const xhr = data.body || {}
const headers = parseHeader(data.headers || {})

xhr.getAllResponseHeaders = function () {
return value.headers
return data.headers
}

xhr.getResponseHeader = function (header) {
Expand Down
6 changes: 5 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ function cache (config = {}) {
const store = config.store
const key = config.key || cache.key

config.maxAge = config.maxAge || 0
config.readCache = config.readCache || readCache
config.serialize = config.serialize || serialize

Expand Down Expand Up @@ -43,7 +44,10 @@ function cache (config = {}) {
const f = () => {
return next()
.then(res => {
return store.setItem(uuid, config.serialize(req, res))
return store.setItem(uuid, {
expires: config.maxAge === 0 ? 0 : Date.now() + config.maxAge,
data: config.serialize(req, res)
})
})
}

Expand Down
18 changes: 15 additions & 3 deletions lib/read-cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import hydrate from './hydrate'
export default function (req, log) {
return function (value) {
return new Promise((resolve, reject) => {
if (!value) {
if (!value || !value.data) {
log('cache-miss', req.url)
const error = new Error()

Expand All @@ -12,6 +12,20 @@ export default function (req, log) {
return reject(error)
}

const { expires, data } = value

if (expires !== 0 && (expires < Date.now())) {
log('cache-stale', req.url)
const error = new Error()

error.reason = 'cache-stale'
error.message = 'Value is stale'
return reject(error)
}

// hydrate pseudo xhr from cached value
req.xhr = hydrate(data)

// override request end callback
req.callback = (err, res) => {
log('cache-hit', req.url)
Expand All @@ -23,8 +37,6 @@ export default function (req, log) {
resolve(res)
}

// hydrate pseudo xhr from cached value
req.xhr = hydrate(value)
req.emit('end')
})
}
Expand Down

0 comments on commit 9809510

Please sign in to comment.