Skip to content

Commit

Permalink
Fix(2788): by preventing invalid route creation (#2790)
Browse files Browse the repository at this point in the history
* Fixes #2788 by preventing invalid route creation

* Explicitly set path on the `HEAD` route opts

* Improve test assertions

Co-authored-by: Manuel Spigolon <behemoth89@gmail.com>

Co-authored-by: Manuel Spigolon <behemoth89@gmail.com>
  • Loading branch information
MSE99 and Eomm committed Jan 25, 2021
1 parent 3634c6e commit f3d5742
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ function buildRouting (options) {
options = Object.assign({}, options, {
method,
url,
path: url,
handler: handler || (options && options.handler)
})

Expand Down Expand Up @@ -163,7 +164,7 @@ function buildRouting (options) {

this.after((notHandledErr, done) => {
const path = opts.url || opts.path
if (path === '/' && prefix.length > 0) {
if (path === '/' && prefix.length > 0 && opts.method !== 'HEAD') {
switch (opts.prefixTrailingSlash) {
case 'slash':
afterRouteAdded.call(this, { path }, notHandledErr, done)
Expand Down
53 changes: 53 additions & 0 deletions test/route.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1060,3 +1060,56 @@ test('Set a custom HEAD route before GET one without disabling exposeHeadRoutes
t.strictEqual(res.body, '')
})
})

test('HEAD routes properly auto created for GET routes when prefixTrailingSlash: \'no-slash\'', t => {
t.plan(2)

const fastify = Fastify()

fastify.register(function routes (f, opts, next) {
f.route({
method: 'GET',
url: '/',
exposeHeadRoute: true,
prefixTrailingSlash: 'no-slash',
handler: (req, reply) => {
reply.send({ hello: 'world' })
}
})

next()
}, { prefix: '/prefix' })

fastify.inject({ url: '/prefix/prefix', method: 'HEAD' }, (err, res) => {
t.error(err)
t.strictEquals(res.statusCode, 404)
})
})

test('HEAD routes properly auto created for GET routes when prefixTrailingSlash: \'both\'', async t => {
t.plan(3)

const fastify = Fastify()

fastify.register(function routes (f, opts, next) {
f.route({
method: 'GET',
url: '/',
exposeHeadRoute: true,
prefixTrailingSlash: 'both',
handler: (req, reply) => {
reply.send({ hello: 'world' })
}
})

next()
}, { prefix: '/prefix' })

const doublePrefixReply = await fastify.inject({ url: '/prefix/prefix', method: 'HEAD' })
const trailingSlashReply = await fastify.inject({ url: '/prefix/', method: 'HEAD' })
const noneTrailingReply = await fastify.inject({ url: '/prefix', method: 'HEAD' })

t.equals(doublePrefixReply.statusCode, 404)
t.equals(trailingSlashReply.statusCode, 200)
t.equals(noneTrailingReply.statusCode, 200)
})

0 comments on commit f3d5742

Please sign in to comment.