Skip to content

Commit

Permalink
Merge pull request #26 from fastify/on-req
Browse files Browse the repository at this point in the history
Use onRequest instead of preHandler
  • Loading branch information
mcollina authored Feb 28, 2019
2 parents e5f0fe1 + 365424e commit a63b760
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
6 changes: 3 additions & 3 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
A plugin for [Fastify](http://fastify.io/) that adds support for reading and
setting cookies.

This plugin's cookie parsing works via Fastify's `preHandler` hook. Therefore,
you should register it prior to any other `preHandler` hooks that will depend
This plugin's cookie parsing works via Fastify's `onRequest` hook. Therefore,
you should register it prior to any other `onRequest` hooks that will depend
upon this plugin's actions.

## Example
Expand All @@ -33,7 +33,7 @@ fastify.get('/', (req, reply) => {

### Parsing

Cookies are parsed in the `preHandler` Fastify hook and attached to the request
Cookies are parsed in the `onRequest` Fastify hook and attached to the request
as an object named `cookies`. Thus, if a request contains the header
`Cookie: foo=foo` then, within your handler, `req.cookies.foo` would equal
`'foo'`.
Expand Down
4 changes: 2 additions & 2 deletions plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function fastifyCookieSetCookie (name, value, options) {
return this
}

function fastifyCookiePreHandler (fastifyReq, fastifyRes, done) {
function fastifyCookieOnReqHandler (fastifyReq, fastifyRes, done) {
const cookieHeader = fastifyReq.req.headers.cookie
fastifyReq.cookies = (cookieHeader) ? cookie.parse(cookieHeader) : {}
done()
Expand All @@ -35,7 +35,7 @@ function fastifyCookiePreHandler (fastifyReq, fastifyRes, done) {
function plugin (fastify, options, next) {
fastify.decorateRequest('cookies', {})
fastify.decorateReply('setCookie', fastifyCookieSetCookie)
fastify.addHook('preHandler', fastifyCookiePreHandler)
fastify.addHook('onRequest', fastifyCookieOnReqHandler)
next()
}

Expand Down
12 changes: 11 additions & 1 deletion test/cookie.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,20 @@ test('cookies get set correctly with millisecond dates', (t) => {
})

test('parses incoming cookies', (t) => {
t.plan(6)
t.plan(6 + 3 * 3)
const fastify = Fastify()
fastify.register(plugin)

// check that it parses the cookies in the onRequest hook
for (let hook of ['preParsing', 'preValidation', 'preHandler']) {
fastify.addHook(hook, (req, reply, done) => {
t.ok(req.cookies)
t.ok(req.cookies.bar)
t.is(req.cookies.bar, 'bar')
done()
})
}

fastify.get('/test2', (req, reply) => {
t.ok(req.cookies)
t.ok(req.cookies.bar)
Expand Down

0 comments on commit a63b760

Please sign in to comment.