Skip to content

Commit

Permalink
fix: converts root parameters with URL object type to a path. (#365)
Browse files Browse the repository at this point in the history
  • Loading branch information
NuktukDev authored Apr 13, 2023
1 parent b0a61ac commit 22fc6a5
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
25 changes: 25 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const path = require('path')
const url = require('url')
const statSync = require('fs').statSync
const { PassThrough } = require('readable-stream')
const glob = require('glob')
Expand All @@ -14,6 +15,7 @@ const encodingNegotiator = require('@fastify/accept-negotiator')
const dirList = require('./lib/dirList')

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

const setHeaders = opts.setHeaders
Expand Down Expand Up @@ -394,6 +396,29 @@ async function fastifyStatic (fastify, opts) {
pumpSendToReply(req, reply, file, rootPath)
}
}
function normalizeRoot (root) {
if (root === undefined) {
return root
}
if (root instanceof URL && root.protocol === 'file:') {
return url.fileURLToPath(root)
}
if (Array.isArray(root)) {
const result = []
for (let i = 0, il = root.length; i < il; ++i) {
if (root[i] instanceof URL && root[i].protocol === 'file:') {
result.push(url.fileURLToPath(root[i]))
} else {
result.push(root[i])
}
}

return result
}

return root
}

function checkRootPathForErrors (fastify, rootPath) {
if (rootPath === undefined) {
throw new Error('"root" option is required')
Expand Down
47 changes: 47 additions & 0 deletions test/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3756,3 +3756,50 @@ t.test(
t.end()
}
)
t.test(
'converts URL to path',
async (t) => {
t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT)
const pluginOptions = {
root: url.pathToFileURL(path.join(__dirname, '/static'))
}

const fastify = Fastify()

fastify.register(fastifyStatic, pluginOptions)
const response = await fastify.inject({
method: 'GET',
url: 'foobar.html',
headers: {
'accept-encoding': '*, *'
}
})
genericResponseChecks(t, response)
t.equal(response.statusCode, 200)
t.same(response.body, foobarContent)
}
)

t.test(
'converts array of URLs to path, contains string path',
async (t) => {
t.plan(2 + GENERIC_RESPONSE_CHECK_COUNT)
const pluginOptions = {
root: [url.pathToFileURL(path.join(__dirname, '/static')), path.join(__dirname, 'static-dotfiles'), url.pathToFileURL(path.join(__dirname, '/static-pre-compressed'))]
}

const fastify = Fastify()

fastify.register(fastifyStatic, pluginOptions)
const response = await fastify.inject({
method: 'GET',
url: 'foobar.html',
headers: {
'accept-encoding': '*, *'
}
})
genericResponseChecks(t, response)
t.equal(response.statusCode, 200)
t.same(response.body, foobarContent)
}
)

0 comments on commit 22fc6a5

Please sign in to comment.