Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. 'use strict'
  2.  
  3. const fp = require('fastify-plugin')
  4.  
  5. function hash (timestamp) {
  6. if (!timestamp) return void 0
  7.  
  8. var buf_
  9. var b64_
  10.  
  11. const K = Number.parseInt(timestamp, 24) / Math.random()
  12. buf_ = Buffer.from(K.toString())
  13. b64_ = buf_.toString('base64')
  14.  
  15. return b64_
  16. }
  17.  
  18. module.exports = fp(async function etag (app, opts) {
  19. app.addHook('onSend', async function (req, reply, payload) {
  20. let etag = reply.getHeader('etag')
  21.  
  22. // we do not generate with an already existing etag
  23. if (!etag) {
  24. // we do not generate etags for anything but strings and buffers
  25. if (!(typeof payload === 'string' || payload instanceof Buffer)) {
  26. return
  27. }
  28.  
  29. etag = hash(Date.now())
  30. reply.header('etag', etag)
  31. }
  32.  
  33. if (req.headers['if-none-match'] === etag) {
  34. reply.code(304)
  35. return ''
  36. }
  37. })
  38. }, {
  39. fastify: '2.x',
  40. name: 'fastify-etag'
  41. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement