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

Do not serialize body values that aren't objects (like FormData) #1316

Merged
Show file tree
Hide file tree
Changes from all commits
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: 2 additions & 2 deletions packages/apollo-datasource-rest/src/RESTDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,8 @@ export abstract class RESTDataSource<TContext = any> {
// We accept arbitrary objects as body and serialize them as JSON
if (
options.body !== undefined &&
typeof options.body !== 'string' &&
!(options.body instanceof ArrayBuffer)
options.body !== null &&
options.body.constructor === Object
) {
options.body = JSON.stringify(options.body);
options.headers.set('Content-Type', 'application/json');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,33 @@ describe('RESTDataSource', () => {
);
});

it('does not serialize a request body that is not an object', async () => {
const dataSource = new class extends RESTDataSource {
baseURL = 'https://api.example.com';

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

dataSource.httpCache = httpCache;

fetch.mockJSONResponseOnce();

// Dumb FormData constructor
function FormData() {}
const form = new FormData();

await dataSource.postFoo(form);

expect(fetch.mock.calls.length).toEqual(1);
expect(fetch.mock.calls[0][0].url).toEqual('https://api.example.com/foo');
expect(fetch.mock.calls[0][0].body).not.toEqual('{}');
expect(fetch.mock.calls[0][0].headers.get('Content-Type')).not.toEqual(
'application/json',
);
});

for (const method of ['GET', 'POST', 'PATCH', 'PUT', 'DELETE']) {
const dataSource = new class extends RESTDataSource {
baseURL = 'https://api.example.com';
Expand Down