Skip to content

Commit

Permalink
fix: respect custom status code when successfully send file (#476)
Browse files Browse the repository at this point in the history
  • Loading branch information
climba03003 authored Oct 17, 2024
1 parent c0ca1c9 commit 5e6aeb9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,11 @@ async function fastifyStatic (fastify, opts) {
break
}
case 'file': {
reply.code(statusCode)
// reply.raw.statusCode by default 200
// when ever the user changed it, we respect the status code
// otherwise use send provided status code
const newStatusCode = reply.statusCode !== 200 ? reply.statusCode : statusCode
reply.code(newStatusCode)
if (setHeaders !== undefined) {
setHeaders(reply.raw, metadata.path, metadata.stat)
}
Expand Down
38 changes: 38 additions & 0 deletions test/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4023,3 +4023,41 @@ t.test('content-length in head route should not return zero when using wildcard'
})
})
})

t.test('respect the .code when using with sendFile', t => {
t.plan(6)

const pluginOptions = {
root: path.join(__dirname, '/static')
}
const fastify = Fastify()

fastify.register(fastifyStatic, pluginOptions)

fastify.get('/custom', (_, reply) => {
return reply.code(404).type('text/html').sendFile('foo.html')
})

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

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

fastify.server.unref()

const file = fs.readFileSync(path.join(__dirname, '/static/foo.html'))
const contentLength = Buffer.byteLength(file).toString()

simple.concat({
method: 'HEAD',
url: 'http://localhost:' + fastify.server.address().port + '/custom',
followRedirect: false
}, (err, response, body) => {
t.error(err)
t.equal(response.statusCode, 404)
t.equal(response.headers['content-type'], 'text/html; charset=UTF-8')
t.equal(response.headers['content-length'], contentLength)
t.equal(body.toString(), '')
})
})
})

0 comments on commit 5e6aeb9

Please sign in to comment.