Skip to content

Instantly share code, notes, and snippets.

@jimmiehansson
Created July 4, 2019 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmiehansson/0b8edb77ffc39edf88338c2f0c5aae0f to your computer and use it in GitHub Desktop.
Save jimmiehansson/0b8edb77ffc39edf88338c2f0c5aae0f to your computer and use it in GitHub Desktop.
Etag rand without added seed and less collision
'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