Skip to content

Commit

Permalink
Adds Support for Generating Weak ETags (#31) (#32)
Browse files Browse the repository at this point in the history
* Adds Support for Generating Weak ETags (#31)

* Adds Support for Generating Weak ETags (#31)

Refactors the buildHashFn function to use external variable for ETag prefix.

Co-authored-by: savearray2 <savearray2>
  • Loading branch information
savearray2 committed Jan 27, 2021
1 parent a6c8e88 commit 3f542c1
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -41,6 +41,8 @@ app.listen(3000)
* `algorithm`: all hashing algorithm that Node.js support, and
`'fnv1a'`. Default: `'fnv1a'`.

* `weak`: generates weak ETags by default. Default: `false`.

## Acknowledgements

The fnv1a logic was forked from https://github.com/sindresorhus/fnv1a
Expand Down
1 change: 1 addition & 0 deletions index.d.ts
Expand Up @@ -3,6 +3,7 @@ import { Server, IncomingMessage, ServerResponse } from 'http';

export interface FastifyEtagOptions {
algorithm?: 'fnv1a' | string;
weak?: false | boolean;
}

declare const fastifyEtag: FastifyPlugin<FastifyEtagOptions>
Expand Down
9 changes: 5 additions & 4 deletions index.js
Expand Up @@ -4,17 +4,18 @@ const fp = require('fastify-plugin')
const { createHash } = require('crypto')
const fnv1a = require('./fnv1a')

function buildHashFn (algorithm = 'fnv1a') {
function buildHashFn (algorithm = 'fnv1a', weak = false) {
const prefix = weak ? 'W/"' : '"'
if (algorithm === 'fnv1a') {
return (payload) => '"' + fnv1a(payload).toString(36) + '"'
return (payload) => prefix + fnv1a(payload).toString(36) + '"'
}

return (payload) => '"' + createHash(algorithm)
return (payload) => prefix + createHash(algorithm)
.update(payload).digest().toString('base64') + '"'
}

module.exports = fp(async function etag (app, opts) {
const hash = buildHashFn(opts.algorithm)
const hash = buildHashFn(opts.algorithm, opts.weak)

app.addHook('onSend', function (req, reply, payload, done) {
let etag = reply.getHeader('etag')
Expand Down
11 changes: 11 additions & 0 deletions test/generic.js
Expand Up @@ -89,4 +89,15 @@ module.exports = function ({ test }, etagOpts, hashFn) {
etag: '"foobar"'
})
})

test('returns a weak etag for each request when weak is in opts', async (t) => {
const res = await build({ weak: true }).inject({
url: '/'
})

t.same(JSON.parse(res.body), { hello: 'world' })
t.match(res.headers, {
etag: 'W/' + hash
})
})
}

0 comments on commit 3f542c1

Please sign in to comment.