Skip to content

Commit

Permalink
support Headers being passed in fetchOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Feb 10, 2024
1 parent 5b6449e commit dc509cc
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/fluffy-poets-protect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@urql/core': patch
---

Correctly support the `Headers` class being used in `fetchOptions`
24 changes: 24 additions & 0 deletions packages/core/src/internal/fetchOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,30 @@ describe('makeFetchOptions', () => {
`);
});

it('handles the Headers object', () => {
const headers = new Headers();
headers.append('x-test', 'true');
const operation = makeOperation(queryOperation.kind, queryOperation, {
...queryOperation.context,
fetchOptions: {
headers,
},
});
const body = makeFetchBody(operation);

expect(makeFetchOptions(operation, body)).toMatchInlineSnapshot(`
{
"body": "{\\"operationName\\":\\"getUser\\",\\"query\\":\\"query getUser($name: String) {\\\\n user(name: $name) {\\\\n id\\\\n firstName\\\\n lastName\\\\n }\\\\n}\\",\\"variables\\":{\\"name\\":\\"Clara\\"}}",
"headers": {
"accept": "application/graphql-response+json, application/graphql+json, application/json, text/event-stream, multipart/mixed",
"content-type": "application/json",
"x-test": "true",
},
"method": "POST",
}
`);
});

it('creates a GET request when preferred for query operations', () => {
const operation = makeOperation(queryOperation.kind, queryOperation, {
...queryOperation.context,
Expand Down
15 changes: 12 additions & 3 deletions packages/core/src/internal/fetchOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,18 @@ export const makeFetchOptions = (
(typeof operation.context.fetchOptions === 'function'
? operation.context.fetchOptions()
: operation.context.fetchOptions) || {};
if (extraOptions.headers)
for (const key in extraOptions.headers)
headers[key.toLowerCase()] = extraOptions.headers[key];
if (extraOptions.headers) {
if (extraOptions.headers.forEach) {
(extraOptions.headers as Headers).forEach((value, key) => {
headers[key] = value;
});
} else {
for (const key in extraOptions.headers) {
headers[key.toLowerCase()] = extraOptions.headers[key];
}
}
}

const serializedBody = serializeBody(operation, body);
if (typeof serializedBody === 'string' && !headers['content-type'])
headers['content-type'] = 'application/json';
Expand Down

0 comments on commit dc509cc

Please sign in to comment.