Skip to content

Commit

Permalink
decorate reply with locals and add on request hook to default to empt…
Browse files Browse the repository at this point in the history
…y object (#351)
  • Loading branch information
Michael Marti committed Nov 2, 2022
1 parent 9170b69 commit 179acef
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
9 changes: 9 additions & 0 deletions index.js
Expand Up @@ -121,6 +121,15 @@ function fastifyView (fastify, opts, next) {
return this
})

if (!fastify.hasReplyDecorator('locals')) {
fastify.decorateReply('locals', null)

fastify.addHook('onRequest', (req, reply, done) => {
reply.locals = {}
done()
})
}

function getPage (page, extension) {
const pageLRU = `getPage-${page}-${extension}`
let result = lru.get(pageLRU)
Expand Down
31 changes: 31 additions & 0 deletions test/test.js
Expand Up @@ -133,6 +133,37 @@ test('reply.view exist', t => {
})
})

test('reply.locals exist', t => {
t.plan(6)
const fastify = Fastify()

fastify.register(require('../index'), {
engine: {
ejs: require('ejs')
}
})

fastify.get('/', (req, reply) => {
t.ok(reply.locals)
reply.send({ hello: 'world' })
})

fastify.listen({ port: 0 }, err => {
t.error(err)

sget({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port
}, (err, response, body) => {
t.error(err)
t.equal(response.statusCode, 200)
t.equal(response.headers['content-length'], '' + body.length)
t.same(JSON.parse(body), { hello: 'world' })
fastify.close()
})
})
})

test('reply.view can be returned from async function to indicate response processing finished', t => {
t.plan(6)
const fastify = Fastify()
Expand Down

0 comments on commit 179acef

Please sign in to comment.