Skip to content

Commit f8b2f53

Browse files
authored
Merge pull request #45 from fastify/config-passing
Add support for passing in extra configuration
2 parents 6a213c6 + 0433476 commit f8b2f53

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,13 @@ Rewrite the prefix to the specified string. Default: `''`.
9494

9595
A `preHandler` to be applied on all routes. Useful for performing actions before the proxy is executed (e.g. check for authentication).
9696

97+
### config
98+
99+
An object accessible within the `preHandler` via `reply.context.config`.
100+
See [Config](https://www.fastify.io/docs/v2.1.x/Routes/#config) in the Fastify
101+
documentation for information on this option. Note: this is merged with other
102+
configuration passed to the route.
103+
97104
### replyOptions
98105

99106
Object with [reply options](https://github.com/fastify/fastify-reply-from#replyfromsource-opts) for `fastify-reply-from`.

index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ module.exports = async function (fastify, opts) {
4040
done(null, req)
4141
}
4242

43-
fastify.all('/', { preHandler }, reply)
44-
fastify.all('/*', { preHandler }, reply)
43+
fastify.all('/', { preHandler, config: opts.config || {} }, reply)
44+
fastify.all('/*', { preHandler, config: opts.config || {} }, reply)
4545

4646
function reply (request, reply) {
4747
var dest = request.req.url

test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,30 @@ async function run () {
141141
t.ok(errored)
142142
})
143143

144+
test('preHandler gets config', async t => {
145+
const server = Fastify()
146+
server.register(proxy, {
147+
upstream: `http://localhost:${origin.server.address().port}`,
148+
config: { foo: 'bar' },
149+
async preHandler (request, reply) {
150+
t.deepEqual(reply.context.config, { foo: 'bar', url: '/*' })
151+
throw new Unauthorized()
152+
}
153+
})
154+
155+
await server.listen(0)
156+
t.tearDown(server.close.bind(server))
157+
158+
var errored = false
159+
try {
160+
await got(`http://localhost:${server.server.address().port}`)
161+
} catch (err) {
162+
t.equal(err.statusCode, 401)
163+
errored = true
164+
}
165+
t.ok(errored)
166+
})
167+
144168
test('beforeHandler(deprecated)', async t => {
145169
const server = Fastify()
146170
server.register(proxy, {

0 commit comments

Comments
 (0)