From 9eccf40241743d91d1ca3cd3d3137024e7b5588e Mon Sep 17 00:00:00 2001 From: liqiang <974923609@qq.com> Date: Mon, 22 Apr 2024 21:28:14 +0800 Subject: [PATCH] weak etag match support (#109) --- index.js | 2 +- test/generic.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index b032bf3..e9820d3 100644 --- a/index.js +++ b/index.js @@ -48,7 +48,7 @@ async function fastifyEtag (app, { algorithm, weak, replyWith304 = true }) { reply.header('etag', etag) } - if (replyWith304 && req.headers['if-none-match'] === etag) { + if (replyWith304 && (req.headers['if-none-match'] === etag || req.headers['if-none-match'] === 'W/' + etag || 'W/' + req.headers['if-none-match'] === etag)) { reply.code(304) newPayload = '' } diff --git a/test/generic.js b/test/generic.js index 03665ea..c2e3a8e 100644 --- a/test/generic.js +++ b/test/generic.js @@ -115,4 +115,52 @@ module.exports = function ({ test }, etagOpts, hashFn) { etag: 'W/' + hash }) }) + + test('returns a 304 if weak etag matches', async (t) => { + const res = await build({ weak: true }).inject({ + url: '/', + headers: { + 'If-None-Match': 'W/' + hash + } + }) + + t.equal(res.statusCode, 304) + t.equal(res.body, '') + t.match(res.headers, { + 'content-length': '0', + etag: 'W/' + hash + }) + }) + + test('returns a 304 if etag is strong and If-None-Match is weak', async (t) => { + const res = await build().inject({ + url: '/', + headers: { + 'If-None-Match': 'W/' + hash + } + }) + + t.equal(res.statusCode, 304) + t.equal(res.body, '') + t.match(res.headers, { + 'content-length': '0', + etag: hash + }) + }) + + test('returns a 304 if etag is weak and If-None-Match is strong', async (t) => { + const res = await build({ weak: true }).inject({ + url: '/', + headers: { + 'If-None-Match': hash + } + }) + + t.equal(res.statusCode, 304) + t.equal(res.body, '') + t.match(res.headers, { + 'content-length': '0', + etag: 'W/' + hash + }) + }) }