Created
July 4, 2019 14:57
-
-
Save jimmiehansson/90a50fddefb29832b824215867237ba5 to your computer and use it in GitHub Desktop.
Etag non secure hash
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 (A) { | |
if (!A) return void 0 | |
var bin_ | |
var buf_ | |
var b64_ | |
bin_ = A.split('').map(c_ => c_.charCodeAt(0).toString(2)).join(' ') | |
const K = Number.parseInt(bin_, 24) / A.length | |
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('test-test') | |
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