Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: automatically decorate etag #116

Merged
merged 1 commit into from
Mar 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const createCompress = require('compress-brotli')
const memoize = require('@keyvhq/memoize')
const Keyv = require('@keyvhq/core')
const assert = require('assert')
const getEtag = require('etag')

const { createKey, isFunction, setHeaders, size } = require('./util')

Expand Down Expand Up @@ -34,11 +33,14 @@ const cacheableResponse = ({
...compressOpts
})

const get = opts => Promise.resolve(rawGet(opts)).then(result => {
if (typeof result !== 'object') return result
result.etag = getEtag(serialize(result))
return result
})
const getEtag = input => require('etag')(serialize(input))

const get = opts =>
Promise.resolve(rawGet(opts)).then(result => {
if (typeof result !== 'object') return result
result.etag = getEtag(result)
return result
})

const memoGet = memoize(get, cache, {
key: getKey,
Expand All @@ -48,7 +50,7 @@ const cacheableResponse = ({
value: compress
})

return async opts => {
const fn = async opts => {
const { req, res } = opts
const [raw, { forceExpiration, hasValue, key, isExpired, isStale }] =
await memoGet(opts)
Expand All @@ -61,7 +63,7 @@ const cacheableResponse = ({
const {
createdAt = Date.now(),
data = null,
etag = getEtag(serialize(result)),
etag = getEtag(result),
staleTtl = memoGet.staleTtl(result),
ttl = memoGet.ttl(result),
...props
Expand Down Expand Up @@ -101,6 +103,10 @@ const cacheableResponse = ({

return send({ data, res, req, ...props })
}

fn.getEtag = getEtag
return fn
}

module.exports = cacheableResponse
module.exports.setHeaders = setHeaders