Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: disable root path check when serve is false #467

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
})
})