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

Fix: Duplicate Content-Type header when Content-Type header is capitalized. #154

Merged
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
4 changes: 4 additions & 0 deletions src/RESTDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,10 @@ export abstract class RESTDataSource {
// If Content-Type header has not been previously set, set to application/json
if (!augmentedRequest.headers) {
augmentedRequest.headers = { 'content-type': 'application/json' };
// replace capitalized content-type header with lower case, ensures no dupliate content-types
} else if (augmentedRequest.headers['Content-Type']) {
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved
augmentedRequest.headers['content-type'] = augmentedRequest.headers['Content-Type'];
delete augmentedRequest.headers['Content-Type'];
} else if (!augmentedRequest.headers['content-type']) {
augmentedRequest.headers['content-type'] = 'application/json';
}
Expand Down
31 changes: 31 additions & 0 deletions src/__tests__/RESTDataSource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,37 @@ describe('RESTDataSource', () => {
await dataSource.getFoo('1');
});

it('contains only one Content-Type header when Content-Type already exists is application/json', async () => {
const requestOptions = {
headers: {
'Content-Type': 'application/json',
},
body: JSON.parse(JSON.stringify({ foo: 'bar' })),
trevor-scheer marked this conversation as resolved.
Show resolved Hide resolved
};
const dataSource = new (class extends RESTDataSource {
override baseURL = 'https://api.example.com';

postFoo() {
return this.post('foo', requestOptions);
}
})();

const spyOnHttpFetch = jest.spyOn(dataSource['httpCache'], 'fetch');

nock(apiUrl)
.post('/foo')
.reply(200, { foo: 'bar' }, { 'Content-Type': 'application/json' });

const data = await dataSource.postFoo();
expect(spyOnHttpFetch.mock.calls[0][1]).toEqual({
headers: {"content-type": "application/json"},
body: "{\"foo\":\"bar\"}",
method: "POST",
params: new URLSearchParams()
})
expect(data).toEqual({ foo: 'bar' });
});

it('serializes a request body that is an object as JSON', async () => {
const expectedFoo = { foo: 'bar' };
const dataSource = new (class extends RESTDataSource {
Expand Down