Skip to content

Commit

Permalink
#223 🐘 do not set Content-Type and Content-Disposition headers if the…
Browse files Browse the repository at this point in the history
…y was set before in response interceptor, test for this
  • Loading branch information
RiceWithMeat committed Jan 24, 2025
1 parent 46921b4 commit fb52c38
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
37 changes: 37 additions & 0 deletions src/core/rest/createRestRoutes/createRestRoutes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,43 @@ describe('createRestRoutes: content', () => {

fs.rmSync(tmpDirPath, { recursive: true, force: true });
});

it('Should not rewrite Content-Type and Content-Disposition headers for file if they was set in interceptor', async () => {
const tmpDirPath = createTmpDir();
const pathToFile = path.join(tmpDirPath, './data.json');
fs.writeFileSync(pathToFile, JSON.stringify({ some: 'data' }));

const server = createServer({
rest: {
configs: [
{
path: '/users',
method: 'get',
routes: [
{
file: pathToFile,
interceptors: {
response: (data, { appendHeader }) => {
appendHeader('content-type', 'text/plain; charset=utf-8');
appendHeader('content-disposition', 'filename=someData.txt');
return data;
}
}
}
]
}
]
}
});

const response = await request(server).get('/users');

expect(response.statusCode).toBe(200);
expect(response.headers['content-type']).toBe('text/plain; charset=utf-8');
expect(response.headers['content-disposition']).toBe('filename=someData.txt');

fs.rmSync(tmpDirPath, { recursive: true, force: true });
});
});

describe('createRestRoutes: settings', () => {
Expand Down
12 changes: 9 additions & 3 deletions src/core/rest/createRestRoutes/createRestRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,15 @@ export const createRestRoutes = ({
}
// ✅ important: replace backslashes because windows can use them in file path
const fileName = data.path.replaceAll('\\', '/').split('/').at(-1)!;
const fileExtension = fileName.split('.').at(-1)!;
response.type(fileExtension);
response.set('Content-Disposition', `filename=${fileName}`);

if (!response.getHeader('content-disposition')) {
response.set('content-disposition', `filename=${fileName}`);
}
if (!response.getHeader('content-type')) {
const fileExtension = fileName.split('.').at(-1)!;
response.type(fileExtension);
}

return response.send(data.file);
}
response.json(data);
Expand Down

0 comments on commit fb52c38

Please sign in to comment.