Skip to content

Commit

Permalink
feat: add timeout and signal arguments to client-side
Browse files Browse the repository at this point in the history
  • Loading branch information
tvervest committed Jul 18, 2024
1 parent 5454c7d commit 6552a1d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
31 changes: 31 additions & 0 deletions src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,35 @@ describe("gqlClientFetch", () => {

expect(gqlResponse).rejects.toThrow();
});

it.only("should use time out after 30 seconds by default", async () => {
const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
fetchMock.mockResponse(responseString);

await fetcher(query, {
myVar: "baz",
});

expect(timeoutSpy).toHaveBeenCalledWith(30000);

// It should not try to POST the query if the persisted query cannot be parsed
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it.only("should use the provided timeout duration", async () => {
const fetcher = initClientFetcher("https://localhost/graphql", {
timeout: 1,
});
const timeoutSpy = vi.spyOn(AbortSignal, "timeout");
fetchMock.mockResponse(responseString);

await fetcher(query, {
myVar: "baz",
});

expect(timeoutSpy).toHaveBeenCalledWith(1);

// It should not try to POST the query if the persisted query cannot be parsed
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
16 changes: 13 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,25 @@ type Options = {
* @default false
*/
persistedQueries?: boolean;

/**
* Sets the timeout duration in ms after which a request will throw a timeout error
*
* @default 30000
*/
timeout?: number;
};

export type ClientFetcher = <TResponse, TVariables>(
astNode: DocumentTypeDecoration<TResponse, TVariables>,
variables?: TVariables
variables?: TVariables,
signal?: AbortSignal
) => Promise<GqlResponse<TResponse>>;

export const initClientFetcher =
(
endpoint: string,
{ persistedQueries = false }: Options = {}
{ persistedQueries = false, timeout = 30000 }: Options = {}
): ClientFetcher =>
/**
* Executes a GraphQL query post request on the client.
Expand All @@ -37,7 +45,8 @@ export const initClientFetcher =
*/
async <TResponse, TVariables>(
astNode: DocumentTypeDecoration<TResponse, TVariables>,
variables?: TVariables
variables?: TVariables,
signal: AbortSignal = AbortSignal.timeout(timeout)
): Promise<GqlResponse<TResponse>> => {
const query = astNode.toString();

Expand Down Expand Up @@ -72,6 +81,7 @@ export const initClientFetcher =
headers: defaultHeaders,
method: "GET",
credentials: "include",
signal,
})
);
}
Expand Down

0 comments on commit 6552a1d

Please sign in to comment.