Skip to content

Commit dc509cc

Browse files
committed
support Headers being passed in fetchOptions
1 parent 5b6449e commit dc509cc

3 files changed

Lines changed: 41 additions & 3 deletions

File tree

.changeset/fluffy-poets-protect.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@urql/core': patch
3+
---
4+
5+
Correctly support the `Headers` class being used in `fetchOptions`

packages/core/src/internal/fetchOptions.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,30 @@ describe('makeFetchOptions', () => {
107107
`);
108108
});
109109

110+
it('handles the Headers object', () => {
111+
const headers = new Headers();
112+
headers.append('x-test', 'true');
113+
const operation = makeOperation(queryOperation.kind, queryOperation, {
114+
...queryOperation.context,
115+
fetchOptions: {
116+
headers,
117+
},
118+
});
119+
const body = makeFetchBody(operation);
120+
121+
expect(makeFetchOptions(operation, body)).toMatchInlineSnapshot(`
122+
{
123+
"body": "{\\"operationName\\":\\"getUser\\",\\"query\\":\\"query getUser($name: String) {\\\\n user(name: $name) {\\\\n id\\\\n firstName\\\\n lastName\\\\n }\\\\n}\\",\\"variables\\":{\\"name\\":\\"Clara\\"}}",
124+
"headers": {
125+
"accept": "application/graphql-response+json, application/graphql+json, application/json, text/event-stream, multipart/mixed",
126+
"content-type": "application/json",
127+
"x-test": "true",
128+
},
129+
"method": "POST",
130+
}
131+
`);
132+
});
133+
110134
it('creates a GET request when preferred for query operations', () => {
111135
const operation = makeOperation(queryOperation.kind, queryOperation, {
112136
...queryOperation.context,

packages/core/src/internal/fetchOptions.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,18 @@ export const makeFetchOptions = (
129129
(typeof operation.context.fetchOptions === 'function'
130130
? operation.context.fetchOptions()
131131
: operation.context.fetchOptions) || {};
132-
if (extraOptions.headers)
133-
for (const key in extraOptions.headers)
134-
headers[key.toLowerCase()] = extraOptions.headers[key];
132+
if (extraOptions.headers) {
133+
if (extraOptions.headers.forEach) {
134+
(extraOptions.headers as Headers).forEach((value, key) => {
135+
headers[key] = value;
136+
});
137+
} else {
138+
for (const key in extraOptions.headers) {
139+
headers[key.toLowerCase()] = extraOptions.headers[key];
140+
}
141+
}
142+
}
143+
135144
const serializedBody = serializeBody(operation, body);
136145
if (typeof serializedBody === 'string' && !headers['content-type'])
137146
headers['content-type'] = 'application/json';

0 commit comments

Comments
 (0)