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

feat(graphiql-toolkit)!: accept HeadersInit #3854

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
12 changes: 12 additions & 0 deletions .changeset/early-pears-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@graphiql/toolkit': minor
'@graphiql/react': patch
---

`graphiql-toolkit` now accepts `HeadersInit` input.

`graphiql-react` has internal type changes to support this.

BREAKING CHANGE:

Because `graphiql-toolkit` functions now accept HeadersInit where previously a partially wider type of `Record<string, unknown>` was accepted, there is a technical backwards incompatibility. This new stricter type could for example cause your project to fail type checking after this upgrade. At runtime, nothing should change since if you weren't already using `string` typed value headers already then they were being coerced implicitly. In practice, this should only serve to marginally improve your code with trivial effort.
jasonkuhrt marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion packages/graphiql-react/src/execution.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export function ExecutionContextProvider({
}

const headersString = headerEditor?.getValue();
let headers: Record<string, unknown> | undefined;
let headers: Record<string, string> | undefined;
try {
headers = tryParseJsonObject({
json: headersString,
Expand Down
2 changes: 1 addition & 1 deletion packages/graphiql-react/src/schema.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ function useIntrospectionQuery({
}

function parseHeaderString(headersString?: string) {
let headers: Record<string, unknown> | null = null;
let headers: Record<string, string> | null = null;
let isValidJSON = true;

try {
Expand Down
2 changes: 1 addition & 1 deletion packages/graphiql-toolkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"dev": "tsup --watch",
"prebuild": "yarn types:check",
"types:check": "tsc --noEmit",
"test": "vitest run"
"test": "vitest"
},
"dependencies": {
"@n1ru4l/push-pull-async-iterable-iterator": "^3.1.0",
Expand Down
36 changes: 36 additions & 0 deletions packages/graphiql-toolkit/src/create-fetcher/__tests__/_helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* eslint-disable */

import { Mock, it as itBase } from 'vitest';

export const test = itBase.extend<{
fetch: Mock<typeof fetch>;
graphqlWs: {
createClient: Mock<
(parameters: { connectionParams: Record<string, string> }) => any
>;
};
}>({
// @ts-expect-error fixme
fetch: async ({}, use) => {
const originalFetch = globalThis.fetch;
const mock = vi
.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ data: {} })));
globalThis.fetch = mock;
await use(fetch);
globalThis.fetch = originalFetch;
},
graphqlWs: async ({}, use) => {
const graphqlWsExports = {
createClient: vi.fn(() => {
return {
subscribe: vi.fn(),
};
}),
};
vi.doMock('graphql-ws', () => {
return graphqlWsExports;
});
await use(graphqlWsExports);
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/* eslint-disable */

import { parse } from 'graphql';
import { createGraphiQLFetcher } from '../createFetcher';
import { test } from './_helpers';

interface TestCase {
constructor: HeadersInit;
send: HeadersInit;
expected: Record<string, string>;
}

const H = Headers;
const cases: TestCase[] = [
// --- levels merge
{ constructor: { a:'1' } , send: { b:'2' } , expected: { a:'1', b:'2' } },
{ constructor: [['a','1']] , send: [['b','2']] , expected: { a:'1', b:'2' } },
{ constructor: new H({a:'1'}) , send: new H({b:'2'}) , expected: { a:'1', b:'2' } },
// --- send level takes precedence
{ constructor: { a:'1' } , send: { a:'2' } , expected: { a:'2' } },
{ constructor: [['a','1']] , send: [['a','2']] , expected: { a:'2' } },
{ constructor: new H({a:'1'}) , send: new H({a:'2'}) , expected: { a:'2' } },
]; // prettier-ignore

describe('accepts HeadersInit on constructor and send levels, send taking precedence', () => {
test.for(cases)('%j', async (_case, { fetch }) => {
const fetcher = createGraphiQLFetcher({
url: 'https://foobar',
enableIncrementalDelivery: false,
headers: _case.constructor,
});
await fetcher({ query: '' }, { headers: _case.send });
// @ts-expect-error
const requestHeaders = Object.fromEntries(new Headers(fetch.mock.calls[0]?.[1]?.headers ?? {}).entries()); // prettier-ignore
expect(fetch).toBeCalledTimes(1);
expect(requestHeaders).toMatchObject(_case.expected);
});

test.for(cases)('incremental delivery: %j', async (_case, { fetch }) => {
const fetcher = createGraphiQLFetcher({
url: 'https://foobar',
enableIncrementalDelivery: true,
headers: _case.constructor,
});
const result = await fetcher({ query: '' }, { headers: _case.send });
// TODO: Improve types to indicate that result is AsyncIterable when enableIncrementalDelivery is true
await drainAsyncIterable(result as AsyncIterable<any>);
// @ts-expect-error
const requestHeaders = Object.fromEntries(new Headers(fetch.mock.calls[0]?.[1]?.headers ?? {}).entries()); // prettier-ignore
expect(fetch).toBeCalledTimes(1);
expect(requestHeaders).toMatchObject(_case.expected);
});

test.for(cases)('subscription: %j', async (_case, { graphqlWs }) => {
const fetcher = createGraphiQLFetcher({
url: 'https://foobar',
headers: _case.constructor,
subscriptionUrl: 'wss://foobar',
});
await fetcher({ query: '', operationName:'foo' }, { headers: _case.send, documentAST: parse('subscription foo { bar }') }); // prettier-ignore
const connectionParams = graphqlWs.createClient.mock.calls[0]?.[0]?.connectionParams ?? {}; // prettier-ignore
expect(graphqlWs.createClient).toBeCalledTimes(1);
expect(connectionParams).toMatchObject(_case.expected);
});
});

// -------------------------------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------------------------------

const drainAsyncIterable = async (iterable: AsyncIterable<any>) => {
const result: any[] = [];
for await (const item of iterable) {
result.push(item);
}
return result;
};
5 changes: 3 additions & 2 deletions packages/graphiql-toolkit/src/create-fetcher/createFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import {
* - optionally supports graphql-ws or `
*/
export function createGraphiQLFetcher(options: CreateFetcherOptions): Fetcher {
const httpFetch =
options.fetch || (typeof window !== 'undefined' && window.fetch);
const httpFetch = options.fetch ?? globalThis.fetch;
if (!httpFetch) {
throw new Error('No valid fetcher implementation available');
}

options.enableIncrementalDelivery =
options.enableIncrementalDelivery !== false;
// simpler fetcher for schema requests
Expand All @@ -29,6 +29,7 @@ export function createGraphiQLFetcher(options: CreateFetcherOptions): Fetcher {

return async (graphQLParams, fetcherOpts) => {
if (graphQLParams.operationName === 'IntrospectionQuery') {
// todo test this
return (options.schemaFetcher || simpleFetcher)(
graphQLParams,
fetcherOpts,
Expand Down
75 changes: 28 additions & 47 deletions packages/graphiql-toolkit/src/create-fetcher/lib.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
// todo
// Current TS Config target does not support `Headers.entries()` method.
// However it is reported as "widely available" and so should be fine to use.
jasonkuhrt marked this conversation as resolved.
Show resolved Hide resolved
// @see https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
// Several places we currently use ts-expect-error to allow this.
jasonkuhrt marked this conversation as resolved.
Show resolved Hide resolved

import { DocumentNode, visit } from 'graphql';
import { meros } from 'meros';
import type {
Expand All @@ -24,23 +30,6 @@ const errorHasCode = (err: unknown): err is { code: string } => {
return typeof err === 'object' && err !== null && 'code' in err;
};

/**
* Merge two Headers instances into one.
*
* Returns a new Headers instance (does not mutate).
*
* Headers are merged by having a copy of the first headers argument apply its `set`
* method to assign each header from the second headers argument. This means that headers
* from the second Headers instance overwrite same-named headers in the first.
*/
const mergeHeadersWithSetStrategy = (headersA: Headers, headersB: Headers) => {
const newHeaders = new Headers(headersA);
for (const [key, value] of headersB.entries()) {
newHeaders.set(key, value);
}
return newHeaders;
};

/**
* Returns true if the name matches a subscription in the AST
*
Expand Down Expand Up @@ -74,14 +63,13 @@ export const isSubscriptionWithName = (
export const createSimpleFetcher =
(options: CreateFetcherOptions, httpFetch: typeof fetch): Fetcher =>
async (graphQLParams: FetcherParams, fetcherOpts?: FetcherOpts) => {
const headers = [
new Headers({
'content-type': 'application/json',
}),
new Headers(options.headers ?? {}),
new Headers(fetcherOpts?.headers ?? {}),
].reduce(mergeHeadersWithSetStrategy, new Headers());

const headers = new Headers({
'content-type': 'application/json',
// @ts-expect-error: todo enable ES target that has entries on headers
...Object.fromEntries(new Headers(options.headers ?? {}).entries()),
// @ts-expect-error: todo enable ES target that has entries on headers
...Object.fromEntries(new Headers(fetcherOpts?.headers ?? {}).entries()),
});
const data = await httpFetch(options.url, {
method: 'POST',
body: JSON.stringify(graphQLParams),
Expand Down Expand Up @@ -162,15 +150,14 @@ export const createMultipartFetcher = (
httpFetch: typeof fetch,
): Fetcher =>
async function* (graphQLParams: FetcherParams, fetcherOpts?: FetcherOpts) {
const headers = [
new Headers({
'content-type': 'application/json',
accept: 'application/json, multipart/mixed',
}),
new Headers(options.headers ?? {}),
new Headers(fetcherOpts?.headers ?? {}),
].reduce(mergeHeadersWithSetStrategy, new Headers());

const headers = new Headers({
'content-type': 'application/json',
accept: 'application/json, multipart/mixed',
// @ts-expect-error: todo enable ES target that has entries on headers
...Object.fromEntries(new Headers(options.headers ?? {}).entries()),
// @ts-expect-error: todo enable ES target that has entries on headers
...Object.fromEntries(new Headers(fetcherOpts?.headers ?? {}).entries()),
});
const response = await httpFetch(options.url, {
method: 'POST',
body: JSON.stringify(graphQLParams),
Expand Down Expand Up @@ -210,21 +197,15 @@ export async function getWsFetcher(
return createWebsocketsFetcherFromClient(options.wsClient);
}
if (options.subscriptionUrl) {
const fetcherOptsHeaders = new Headers(fetcherOpts?.headers ?? {});
// @ts-expect-error: Current TS Config target does not support `Headers.entries()` method.
// However it is reported as "widely available" and so should be fine to use. This could
// would be more complicated without it.
// @see https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries
const fetcherOptsHeadersEntries: [string, string][] = [
...fetcherOptsHeaders.entries(),
];
// todo: If there are headers with multiple values, they will be lost. Is this a problem?
const fetcherOptsHeadersRecord = Object.fromEntries(
fetcherOptsHeadersEntries,
);
const headers = {
// @ts-expect-error: todo enable ES target that has entries on headers
...Object.fromEntries(new Headers(options?.headers ?? {}).entries()),
// @ts-expect-error: todo enable ES target that has entries on headers
...Object.fromEntries(new Headers(fetcherOpts?.headers ?? {}).entries()),
};
return createWebsocketsFetcherFromUrl(options.subscriptionUrl, {
...options.wsConnectionParams,
...fetcherOptsHeadersRecord,
...headers,
});
}
const legacyWebsocketsClient = options.legacyClient || options.legacyWsClient;
Expand Down