From c88914b812ff9d9cc988c53cfe49eefa368f0387 Mon Sep 17 00:00:00 2001 From: KaKa Date: Wed, 16 Oct 2024 16:43:07 +0800 Subject: [PATCH] fix: respect custom status code when successfully send file --- index.js | 6 +++++- test/static.test.js | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 99d8e4e2..e7c20717 100644 --- a/index.js +++ b/index.js @@ -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) } diff --git a/test/static.test.js b/test/static.test.js index 608d57ac..45e2663d 100644 --- a/test/static.test.js +++ b/test/static.test.js @@ -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(), '') + }) + }) +})