Created
July 4, 2019 12:25
-
-
Save jimmiehansson/0b8edb77ffc39edf88338c2f0c5aae0f to your computer and use it in GitHub Desktop.
Etag rand without added seed and less collision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const fp = require('fastify-plugin') | |
function hash (timestamp) { | |
if (!timestamp) return void 0 | |
var buf_ | |
var b64_ | |
const K = Number.parseInt(timestamp, 24) / Math.random() | |
buf_ = Buffer.from(K.toString()) | |
b64_ = buf_.toString('base64') | |
return b64_ | |
} | |
module.exports = fp(async function etag (app, opts) { | |
app.addHook('onSend', async function (req, reply, payload) { | |
let etag = reply.getHeader('etag') | |
// we do not generate with an already existing etag | |
if (!etag) { | |
// we do not generate etags for anything but strings and buffers | |
if (!(typeof payload === 'string' || payload instanceof Buffer)) { | |
return | |
} | |
etag = hash(Date.now()) | |
reply.header('etag', etag) | |
} | |
if (req.headers['if-none-match'] === etag) { | |
reply.code(304) | |
return '' | |
} | |
}) | |
}, { | |
fastify: '2.x', | |
name: 'fastify-etag' | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment