Skip to content

Commit

Permalink
feature: disable root path check when serve is false
Browse files Browse the repository at this point in the history
  • Loading branch information
nimesh0505 committed Sep 2, 2024
1 parent 39e89ea commit 8c39dca
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ send.mime.default_type = 'application/octet-stream'

async function fastifyStatic (fastify, opts) {
opts.root = normalizeRoot(opts.root)
checkRootPathForErrors(fastify, opts.root)
checkRootPathForErrors(fastify, opts.root, opts.serve)

const setHeaders = opts.setHeaders
if (setHeaders !== undefined && typeof setHeaders !== 'function') {
Expand Down Expand Up @@ -408,7 +408,11 @@ function normalizeRoot (root) {
return root
}

function checkRootPathForErrors (fastify, rootPath) {
function checkRootPathForErrors (fastify, rootPath, serve = true) {
if (serve === false) {
return
}

if (rootPath === undefined) {
throw new Error('"root" option is required')
}
Expand Down
48 changes: 48 additions & 0 deletions test/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4023,3 +4023,51 @@ t.test('content-length in head route should not return zero when using wildcard'
})
})
})

t.test('serve: false disables root path check', (t) => {
t.plan(3)

const pluginOptions = {
root: path.join(__dirname, '/static'),
prefix: '/static',
serve: false
}
const fastify = Fastify()
fastify.register(fastifyStatic, pluginOptions)

t.teardown(fastify.close.bind(fastify))

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

fastify.server.unref()

t.test('/static/index.html', (t) => {
t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT)
simple.concat({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + '/static/index.html'
}, (err, response, body) => {
t.error(err)
t.equal(response.statusCode, 404)
genericErrorResponseChecks(t, response)
t.end()
})
})

t.test('/static/deep/path/for/test/purpose/foo.html', (t) => {
t.plan(2 + GENERIC_ERROR_RESPONSE_CHECK_COUNT)
simple.concat({
method: 'GET',
url: 'http://localhost:' + fastify.server.address().port + '/static/deep/path/for/test/purpose/foo.html'
}, (err, response, body) => {
t.error(err)
t.equal(response.statusCode, 404)
genericErrorResponseChecks(t, response)
t.end()
})
})

t.end()
})
})

0 comments on commit 8c39dca

Please sign in to comment.