@hyper-fetch/graphql 9.9.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +152 -84
  2. package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
  3. package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
  4. package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
  5. package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
  6. package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
  7. package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
  8. package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
  9. package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
  10. package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
  11. package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
  12. package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
  13. package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
  14. package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
  15. package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
  16. package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
  17. package/__tests__/features/socket/socket.connection.spec.ts +892 -0
  18. package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
  19. package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
  20. package/__tests__/features/socket/socket.types.spec.ts +160 -0
  21. package/__tests__/utils/controlled-websocket.ts +238 -0
  22. package/dist/adapter/adapter.constants.d.ts +5 -0
  23. package/dist/adapter/adapter.constants.d.ts.map +1 -1
  24. package/dist/adapter/adapter.types.d.ts +55 -2
  25. package/dist/adapter/adapter.types.d.ts.map +1 -1
  26. package/dist/adapter/adapter.utils.d.ts +51 -4
  27. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  28. package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.mjs +958 -128
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/socket/index.d.ts +5 -0
  34. package/dist/socket/index.d.ts.map +1 -0
  35. package/dist/socket/socket.constants.d.ts +44 -0
  36. package/dist/socket/socket.constants.d.ts.map +1 -0
  37. package/dist/socket/socket.subscriptions.d.ts +74 -0
  38. package/dist/socket/socket.subscriptions.d.ts.map +1 -0
  39. package/dist/socket/socket.types.d.ts +102 -0
  40. package/dist/socket/socket.types.d.ts.map +1 -0
  41. package/dist/socket/socket.utils.d.ts +80 -0
  42. package/dist/socket/socket.utils.d.ts.map +1 -0
  43. package/dist/socket/socket.websocket.d.ts +30 -0
  44. package/dist/socket/socket.websocket.d.ts.map +1 -0
  45. package/package.json +14 -9
  46. package/src/adapter/adapter.constants.ts +6 -0
  47. package/src/adapter/adapter.types.ts +69 -3
  48. package/src/adapter/adapter.utils.ts +196 -25
  49. package/src/adapter/http-adapter.fetch.ts +93 -43
  50. package/src/index.ts +1 -0
  51. package/src/socket/index.ts +4 -0
  52. package/src/socket/socket.constants.ts +59 -0
  53. package/src/socket/socket.subscriptions.ts +160 -0
  54. package/src/socket/socket.types.ts +118 -0
  55. package/src/socket/socket.utils.ts +150 -0
  56. package/src/socket/socket.websocket.ts +555 -0
  57. package/vite.config.ts +4 -0
@@ -44,7 +44,7 @@ describe("Graphql Adapter [ Browser ]", () => {
44
44
  expect(status).toBe(200);
45
45
  expect(error).toBe(null);
46
46
  expect(extra).toStrictEqual({
47
- headers: { "content-type": "application/json", "content-length": "48" },
47
+ headers: { "content-type": "application/graphql-response+json", "content-length": "48" },
48
48
  extensions: {},
49
49
  });
50
50
  });
@@ -58,7 +58,7 @@ describe("Graphql Adapter [ Browser ]", () => {
58
58
  expect(status).toBe(200);
59
59
  expect(error).toBe(null);
60
60
  expect(extra).toStrictEqual({
61
- headers: { "content-type": "application/json", "content-length": "48" },
61
+ headers: { "content-type": "application/graphql-response+json", "content-length": "48" },
62
62
  extensions: {},
63
63
  });
64
64
  });
@@ -72,8 +72,9 @@ describe("Graphql Adapter [ Browser ]", () => {
72
72
  expect(status).toBe(400);
73
73
  expect(error).toStrictEqual(expected.errors);
74
74
  expect(extra).toStrictEqual({
75
- headers: { "content-type": "application/json", "content-length": "42" },
75
+ headers: { "content-type": "application/graphql-response+json", "content-length": "42" },
76
76
  extensions: {},
77
+ errors: expected.errors,
77
78
  });
78
79
  });
79
80
 
@@ -97,7 +98,7 @@ describe("Graphql Adapter [ Browser ]", () => {
97
98
  expect(status).toBe(200);
98
99
  expect(error).toBe(null);
99
100
  expect(extra).toStrictEqual({
100
- headers: { "content-type": "application/json", "content-length": "48" },
101
+ headers: { "content-type": "application/graphql-response+json", "content-length": "48" },
101
102
  extensions: {},
102
103
  });
103
104
  });
@@ -115,6 +116,23 @@ describe("Graphql Adapter [ Browser ]", () => {
115
116
  expect(error).toStrictEqual([getErrorMessage("abort")]);
116
117
  });
117
118
 
119
+ it("should report aborted requests as canceled and not retry them", async () => {
120
+ mockRequest(request, { delay: 50 });
121
+ const retried = request.setRetry(2).setRetryTime(0);
122
+ const onResponse = vi.fn();
123
+ client.requestManager.events.onResponse(onResponse);
124
+ const unmount = client.requestManager.events.onRequestStart(() => {
125
+ unmount();
126
+ retried.abort();
127
+ });
128
+
129
+ const { success } = await retried.send();
130
+
131
+ expect(success).toBeFalse();
132
+ expect(onResponse).toHaveBeenCalledOnce();
133
+ expect(onResponse.mock.calls[0][0].details).toMatchObject({ isCanceled: true, willRetry: false });
134
+ });
135
+
118
136
  // it("should not throw when XMLHttpRequest is not available on window", async () => {
119
137
  // const expected = mockRequest(request, { delay: 20 });
120
138
  // const xml = window.XMLHttpRequest;
@@ -140,7 +158,7 @@ describe("Graphql Adapter [ Browser ]", () => {
140
158
 
141
159
  expect(data).toBeNull();
142
160
  expect(status).toBe(0);
143
- expect(error).toStrictEqual(getErrorMessage("timeout"));
161
+ expect(error).toStrictEqual([getErrorMessage("timeout")]);
144
162
  });
145
163
 
146
164
  it("should handle undefined response data as null", async () => {
@@ -25,15 +25,15 @@ describe("Graphql Adapter [ Document and query params ]", () => {
25
25
  const { fullUrl, payload } = getRequestValues(request);
26
26
 
27
27
  expect(fullUrl).toBe(url);
28
- expect(payload).toBe(JSON.stringify({ query: printedQuery }));
28
+ expect(payload).toBe(JSON.stringify({ query: printedQuery, operationName: "GetUser" }));
29
29
  expect(getGqlDocument(request)).toBe(printedQuery);
30
30
  });
31
31
 
32
- it("should keep the same keys as before", () => {
32
+ it("should key the operation name and the document fingerprint", () => {
33
33
  const request = client.createRequest()({ endpoint: getUserQueryString });
34
34
 
35
- expect(request.cacheKey).toBe("POST_GetUser--");
36
- expect(request.queryKey).toBe("POST_GetUser--");
35
+ expect(request.cacheKey).toMatch(/^POST_GetUser@\w+--$/);
36
+ expect(request.queryKey).toMatch(/^POST_GetUser@\w+--$/);
37
37
  expect(request.abortKey).toBe("POST_GetUser-false");
38
38
  });
39
39
 
@@ -45,7 +45,7 @@ describe("Graphql Adapter [ Document and query params ]", () => {
45
45
  const { fullUrl, payload } = getRequestValues(request);
46
46
 
47
47
  expect(fullUrl).toBe(`${url}?source=app`);
48
- expect(payload).toBe(JSON.stringify({ query: printedQuery }));
48
+ expect(payload).toBe(JSON.stringify({ query: printedQuery, operationName: "GetUser" }));
49
49
  });
50
50
 
51
51
  it("should merge query params into the GET query string", () => {
@@ -69,7 +69,7 @@ describe("Graphql Adapter [ Document and query params ]", () => {
69
69
  const { fullUrl, payload } = getRequestValues(request);
70
70
 
71
71
  expect(fullUrl).toBe(`${url}/User`);
72
- expect(payload).toBe(JSON.stringify({ query: printedQuery }));
72
+ expect(payload).toBe(JSON.stringify({ query: printedQuery, operationName: "GetUser" }));
73
73
  expect(request.endpoint).toBe("/User");
74
74
  expect(getGqlDocument(request)).toBe(getUserQuery);
75
75
  });
@@ -77,7 +77,9 @@ describe("Graphql Adapter [ Document and query params ]", () => {
77
77
  it("should send a string document as it is", () => {
78
78
  const request = client.createRequest()({ endpoint: "/User", document: getUserQueryString });
79
79
 
80
- expect(getRequestValues(request).payload).toBe(JSON.stringify({ query: getUserQueryString }));
80
+ expect(getRequestValues(request).payload).toBe(
81
+ JSON.stringify({ query: getUserQueryString, operationName: "GetUser" }),
82
+ );
81
83
  });
82
84
 
83
85
  it("should build the url from the issue example", () => {
@@ -89,7 +91,7 @@ describe("Graphql Adapter [ Document and query params ]", () => {
89
91
  const { fullUrl, payload } = getRequestValues(request);
90
92
 
91
93
  expect(fullUrl).toBe(`${url}/User?source=app&build=1.2.3`);
92
- expect(payload).toBe(JSON.stringify({ query: printedQuery, variables: { id: 1 } }));
94
+ expect(payload).toBe(JSON.stringify({ query: printedQuery, operationName: "GetUser", variables: { id: 1 } }));
93
95
  });
94
96
 
95
97
  it("should send everything in the query string for GET", () => {
@@ -126,7 +128,7 @@ describe("Graphql Adapter [ Document and query params ]", () => {
126
128
  const { fullUrl, payload } = getRequestValues(request.setParams({ tenantId: 7 }));
127
129
 
128
130
  expect(fullUrl).toBe(`${url}/tenant/7/User`);
129
- expect(payload).toBe(JSON.stringify({ query: printedQuery }));
131
+ expect(payload).toBe(JSON.stringify({ query: printedQuery, operationName: "GetUser" }));
130
132
  });
131
133
 
132
134
  it("should treat nullish document as omitted", () => {
@@ -152,7 +154,9 @@ describe("Graphql Adapter [ Document and query params ]", () => {
152
154
  const hydrated = client.fromJSON(restored);
153
155
 
154
156
  expect(getRequestValues(hydrated as any).fullUrl).toBe(`${url}/User`);
155
- expect(getRequestValues(hydrated as any).payload).toBe(JSON.stringify({ query: printedQuery }));
157
+ expect(getRequestValues(hydrated as any).payload).toBe(
158
+ JSON.stringify({ query: printedQuery, operationName: "GetUser" }),
159
+ );
156
160
  expect(hydrated.cacheKey).toBe(request.cacheKey);
157
161
  });
158
162
  });
@@ -280,8 +284,8 @@ describe("Graphql Adapter [ Document and query params ]", () => {
280
284
  const fromString = client.createRequest()({ endpoint: "/User", document: getUserQueryString });
281
285
 
282
286
  [fromNode, fromString].forEach((request) => {
283
- expect(request.cacheKey).toBe("POST_GetUser/User--");
284
- expect(request.queryKey).toBe("POST_GetUser/User--");
287
+ expect(request.cacheKey).toMatch(/^POST_GetUser\/User@\w+--$/);
288
+ expect(request.queryKey).toMatch(/^POST_GetUser\/User@\w+--$/);
285
289
  expect(request.abortKey).toBe("POST_GetUser/User-false");
286
290
  });
287
291
  });
@@ -289,7 +293,7 @@ describe("Graphql Adapter [ Document and query params ]", () => {
289
293
  it("should not add the path for the empty endpoint", () => {
290
294
  const request = client.createRequest()({ endpoint: "", document: getUserQuery });
291
295
 
292
- expect(request.cacheKey).toBe("POST_GetUser--");
296
+ expect(request.cacheKey).toMatch(/^POST_GetUser@\w+--$/);
293
297
  });
294
298
 
295
299
  it("should distinguish the same operation sent to different paths", () => {
@@ -0,0 +1,65 @@
1
+ import { Client } from "@hyper-fetch/core";
2
+ import { GraphqlAdapter, GraphqlMethod } from "adapter";
3
+
4
+ const url = "https://shared-base-url/graphql";
5
+ const getUsers = "query GetUsers { users { name } }";
6
+ // Typed as a plain string: a literal would also make the adapter infer the variables from the query text
7
+ const getUser = "query GetUser($id: ID!) { user(id: $id) { name } }" as string;
8
+
9
+ /**
10
+ * A POST body is always the JSON `{ query, variables }`, so servers that check the content type (GraphQL over HTTP
11
+ * spec, Apollo CSRF prevention) need `application/json` even when the operation has no variables.
12
+ */
13
+ describe("Graphql Adapter [ Headers ]", () => {
14
+ let client = new Client({ url }).setAdapter(GraphqlAdapter());
15
+ let fetchSpy = vi.spyOn(globalThis, "fetch");
16
+
17
+ const getSentHeaders = () => new Headers(fetchSpy.mock.calls[0][1]?.headers);
18
+
19
+ beforeEach(() => {
20
+ client = new Client({ url }).setAdapter(GraphqlAdapter());
21
+ fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => Response.json({ data: { users: [] } }));
22
+ });
23
+
24
+ afterEach(() => {
25
+ fetchSpy.mockRestore();
26
+ });
27
+
28
+ it("should send the JSON content type for a query without variables", async () => {
29
+ await client.createRequest()({ endpoint: getUsers }).send();
30
+
31
+ expect(getSentHeaders().get("content-type")).toBe("application/json");
32
+ });
33
+
34
+ it("should send the JSON content type for a query with variables", async () => {
35
+ await client
36
+ .createRequest<{ payload: { id: string } }>()({ endpoint: getUser })
37
+ .send({ payload: { id: "1" } });
38
+
39
+ expect(getSentHeaders().get("content-type")).toBe("application/json");
40
+ });
41
+
42
+ it("should not send a content type for a GET request without a body", async () => {
43
+ await client.createRequest()({ endpoint: getUsers, method: GraphqlMethod.GET }).send();
44
+
45
+ expect(fetchSpy.mock.calls[0][1]?.body).toBeUndefined();
46
+ expect(getSentHeaders().has("content-type")).toBeFalse();
47
+ });
48
+
49
+ it("should not send a content type for a GET request with variables in the URL", async () => {
50
+ await client
51
+ .createRequest<{ payload: { id: string } }>()({ endpoint: getUser, method: GraphqlMethod.GET })
52
+ .send({ payload: { id: "1" } });
53
+
54
+ expect(String(fetchSpy.mock.calls[0][0])).toContain("variables=");
55
+ expect(getSentHeaders().has("content-type")).toBeFalse();
56
+ });
57
+
58
+ it("should keep the content type given with the request", async () => {
59
+ await client
60
+ .createRequest()({ endpoint: getUsers, headers: { "content-type": "application/graphql-response+json" } })
61
+ .send();
62
+
63
+ expect(getSentHeaders().get("content-type")).toBe("application/graphql-response+json");
64
+ });
65
+ });
@@ -0,0 +1,235 @@
1
+ import type { RequestInstance } from "@hyper-fetch/core";
2
+ import { Client } from "@hyper-fetch/core";
3
+ import { GraphqlAdapter, GraphqlMethod, matchGqlOperation } from "adapter";
4
+ import gql from "graphql-tag";
5
+
6
+ const url = "https://shared-base-url/graphql";
7
+
8
+ type UserResponse = { user: { name?: string; email?: string } };
9
+
10
+ /**
11
+ * Two documents can share the operation name, or the root field when they are anonymous, and still select other
12
+ * fields. They are other queries: sharing a cache entry would hand one component the data shaped for another.
13
+ */
14
+ describe("Graphql Adapter [ Keys ]", () => {
15
+ // The cache is only kept in the "client" mode
16
+ const createClient = () => new Client({ url, mode: "client" }).setAdapter(GraphqlAdapter());
17
+
18
+ let client = createClient();
19
+ let fetchSpy = vi.spyOn(globalThis, "fetch");
20
+
21
+ /** Answer with the fields the sent document selects */
22
+ const answerWithSelectedFields = () => {
23
+ fetchSpy.mockImplementation(async (_input, init) => {
24
+ const { query } = JSON.parse(String(init?.body));
25
+ const user = String(query).includes("email") ? { email: "ann@example.com" } : { name: "Ann" };
26
+ return Response.json({ data: { user } });
27
+ });
28
+ };
29
+
30
+ beforeEach(() => {
31
+ client = createClient();
32
+ fetchSpy = vi.spyOn(globalThis, "fetch");
33
+ });
34
+
35
+ afterEach(() => {
36
+ fetchSpy.mockRestore();
37
+ });
38
+
39
+ it.each([
40
+ ["named operations", "query GetUser { user { name } }", "query GetUser { user { email } }"],
41
+ ["anonymous operations", "{ user { name } }", "{ user { email } }"],
42
+ ])("should give %s with other selections their own keys", (_name, withName, withEmail) => {
43
+ const first = client.createRequest<{ response: UserResponse }>()({ endpoint: withName });
44
+ const second = client.createRequest<{ response: UserResponse }>()({ endpoint: withEmail });
45
+
46
+ expect(first.cacheKey).not.toBe(second.cacheKey);
47
+ expect(first.queryKey).not.toBe(second.queryKey);
48
+ });
49
+
50
+ it("should give DocumentNodes with other selections their own keys", () => {
51
+ const first = client.createRequest<{ response: UserResponse }>()({
52
+ endpoint: gql`
53
+ query GetUser {
54
+ user {
55
+ name
56
+ }
57
+ }
58
+ `,
59
+ });
60
+ const second = client.createRequest<{ response: UserResponse }>()({
61
+ endpoint: gql`
62
+ query GetUser {
63
+ user {
64
+ email
65
+ }
66
+ }
67
+ `,
68
+ });
69
+
70
+ expect(first.cacheKey).not.toBe(second.cacheKey);
71
+ });
72
+
73
+ it("should give the same document passed by the document option and other paths their own keys", () => {
74
+ const document = "query GetUser { user { name } }";
75
+ const first = client.createRequest<{ response: UserResponse }>()({ endpoint: "/a", document });
76
+ const second = client.createRequest<{ response: UserResponse }>()({
77
+ endpoint: "/a",
78
+ document: "{ user { email } }",
79
+ });
80
+
81
+ expect(first.cacheKey).not.toBe(second.cacheKey);
82
+ });
83
+
84
+ it("should keep the data of each document in its own cache entry", async () => {
85
+ answerWithSelectedFields();
86
+ const withName = client.createRequest<{ response: UserResponse }>()({
87
+ endpoint: "query GetUser { user { name } }",
88
+ });
89
+ const withEmail = client.createRequest<{ response: UserResponse }>()({
90
+ endpoint: "query GetUser { user { email } }",
91
+ });
92
+
93
+ await withName.send();
94
+ await withEmail.send();
95
+
96
+ expect(client.cache.get(withName.cacheKey)?.data).toEqual({ user: { name: "Ann" } });
97
+ expect(client.cache.get(withEmail.cacheKey)?.data).toEqual({ user: { email: "ann@example.com" } });
98
+ });
99
+
100
+ it("should not deduplicate documents with other selections into one request", async () => {
101
+ answerWithSelectedFields();
102
+ const withName = client
103
+ .createRequest<{ response: UserResponse }>()({ endpoint: "query GetUser { user { name } }" })
104
+ .setDeduplicate(true);
105
+ const withEmail = client
106
+ .createRequest<{ response: UserResponse }>()({ endpoint: "query GetUser { user { email } }" })
107
+ .setDeduplicate(true);
108
+
109
+ const [first, second] = await Promise.all([withName.send(), withEmail.send()]);
110
+
111
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
112
+ expect(first.data).toEqual({ user: { name: "Ann" } });
113
+ expect(second.data).toEqual({ user: { email: "ann@example.com" } });
114
+ });
115
+
116
+ it("should give the same document the same keys", () => {
117
+ const document = "query GetUser { user { name } }";
118
+
119
+ expect(client.createRequest()({ endpoint: document }).cacheKey).toBe(
120
+ client.createRequest()({ endpoint: document }).cacheKey,
121
+ );
122
+ });
123
+
124
+ it("should keep one abort key for an operation name, whatever its selection", () => {
125
+ const first = client.createRequest()({ endpoint: "query GetUser { user { name } }" });
126
+ const second = client.createRequest()({ endpoint: "query GetUser { user { email } }" });
127
+
128
+ expect(first.abortKey).toBe(second.abortKey);
129
+ });
130
+ });
131
+
132
+ /** Refetching every variant of an operation after a mutation - `refetchQueries` in Apollo */
133
+ describe("Graphql Adapter [ Operation matcher ]", () => {
134
+ const createClient = () => new Client({ url, mode: "client" }).setAdapter(GraphqlAdapter());
135
+ const getUser = "query GetUser($id: ID!) { user(id: $id) { name } }";
136
+ const getUserEmail = "query GetUser($id: ID!) { user(id: $id) { email } }";
137
+
138
+ let client = createClient();
139
+ let fetchSpy = vi.spyOn(globalThis, "fetch");
140
+
141
+ beforeEach(() => {
142
+ client = createClient();
143
+ fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => Response.json({ data: { user: {} } }));
144
+ });
145
+
146
+ afterEach(() => {
147
+ fetchSpy.mockRestore();
148
+ });
149
+
150
+ /** Send the request, so its response is cached under its cache key */
151
+ const cacheRequest = async (request: RequestInstance) => {
152
+ await request.send();
153
+ return request.cacheKey;
154
+ };
155
+
156
+ const isStale = (cacheKey: string) => client.cache.get(cacheKey)?.staleTime === 0;
157
+
158
+ it("should match every variant of a document", async () => {
159
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({ endpoint: getUser });
160
+ const first = await cacheRequest(request.setPayload({ id: 1 }));
161
+ const second = await cacheRequest(request.setPayload({ id: 2 }));
162
+ const asGet = await cacheRequest(
163
+ client
164
+ .createRequest<{ response: UserResponse; payload: { id: number } }>()({
165
+ endpoint: getUser,
166
+ method: GraphqlMethod.GET,
167
+ })
168
+ .setPayload({ id: 3 }),
169
+ );
170
+ const otherSelection = await cacheRequest(
171
+ client
172
+ .createRequest<{ response: UserResponse; payload: { id: number } }>()({ endpoint: getUserEmail })
173
+ .setPayload({
174
+ id: 1,
175
+ }),
176
+ );
177
+
178
+ expect([first, second, asGet, otherSelection].map(isStale)).toStrictEqual([false, false, false, false]);
179
+
180
+ client.cache.invalidate(matchGqlOperation(getUser));
181
+
182
+ expect([first, second, asGet].map(isStale)).toStrictEqual([true, true, true]);
183
+ expect(isStale(otherSelection)).toBeFalse();
184
+ });
185
+
186
+ it("should match a DocumentNode like the request built from it", async () => {
187
+ const document = gql`
188
+ query GetUser($id: ID!) {
189
+ user(id: $id) {
190
+ name
191
+ }
192
+ }
193
+ `;
194
+ const cacheKey = await cacheRequest(
195
+ client.createRequest<{ response: UserResponse; payload: { id: number } }>()({ endpoint: document }).setPayload({
196
+ id: 1,
197
+ }),
198
+ );
199
+
200
+ expect(matchGqlOperation(document).test(cacheKey)).toBeTrue();
201
+ });
202
+
203
+ it("should match the document on every url path of the document option", () => {
204
+ const first = client.createRequest()({ endpoint: "/a", document: getUser });
205
+ const second = client.createRequest()({ endpoint: "/tenant/:tenantId/b", document: getUser }).setParams({
206
+ tenantId: 1,
207
+ });
208
+
209
+ expect(matchGqlOperation(getUser).test(first.cacheKey)).toBeTrue();
210
+ expect(matchGqlOperation(getUser).test(second.cacheKey)).toBeTrue();
211
+ });
212
+
213
+ it("should match only the url path of a request", () => {
214
+ const onA = client.createRequest()({ endpoint: "/a", document: getUser });
215
+ const onB = client.createRequest()({ endpoint: "/b", document: getUser });
216
+
217
+ expect(matchGqlOperation(onA).test(onA.setQueryParams({ x: 1 }).cacheKey)).toBeTrue();
218
+ expect(matchGqlOperation(onA).test(onB.cacheKey)).toBeFalse();
219
+ });
220
+
221
+ it("should not let regular expression characters in the path widen the match", () => {
222
+ const dotted = client.createRequest()({ endpoint: "/a.b", document: getUser });
223
+ const other = client.createRequest()({ endpoint: "/aXb", document: getUser });
224
+
225
+ expect(matchGqlOperation(dotted).test(other.cacheKey)).toBeFalse();
226
+ });
227
+
228
+ it("should match every variant when it is used more than once", () => {
229
+ const matcher = matchGqlOperation(getUser);
230
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({ endpoint: getUser });
231
+
232
+ expect(matcher.test(request.setPayload({ id: 1 }).cacheKey)).toBeTrue();
233
+ expect(matcher.test(request.setPayload({ id: 2 }).cacheKey)).toBeTrue();
234
+ });
235
+ });
@@ -0,0 +1,207 @@
1
+ import { Client } from "@hyper-fetch/core";
2
+ import { GraphqlAdapter, GraphqlMethod } from "adapter";
3
+ import { createHash } from "node:crypto";
4
+
5
+ const url = "https://shared-base-url/graphql";
6
+ const query = "query GetUser { user { name } }";
7
+ const sha256Hash = createHash("sha256").update(query).digest("hex");
8
+ const persistedQuery = { version: 1, sha256Hash };
9
+
10
+ type UserResponse = { user: { name: string } };
11
+
12
+ /**
13
+ * Automatic persisted queries: the hash goes first, the full query only when the server does not know it yet.
14
+ * Hashed GET requests stay short, so CDNs can cache them.
15
+ */
16
+ describe("Graphql Adapter [ Persisted queries ]", () => {
17
+ let client = new Client({ url }).setAdapter(GraphqlAdapter());
18
+ let fetchSpy = vi.spyOn(globalThis, "fetch");
19
+
20
+ const json = (body: unknown, status = 200) => Response.json(body, { status });
21
+ const notFound = { errors: [{ message: "PersistedQueryNotFound" }] };
22
+ const notSupported = { errors: [{ message: "PersistedQueryNotSupported" }] };
23
+ const user = { data: { user: { name: "Ann" } } };
24
+
25
+ const createRequest = (method: GraphqlMethod = GraphqlMethod.POST) =>
26
+ client.createRequest<{ response: UserResponse }>()({
27
+ endpoint: query,
28
+ method,
29
+ options: { persistedQueries: true },
30
+ });
31
+
32
+ const sentBody = (call: number) => JSON.parse(String(fetchSpy.mock.calls[call][1]?.body));
33
+ const sentParams = (call: number) => new URL(String(fetchSpy.mock.calls[call][0])).searchParams;
34
+
35
+ beforeEach(() => {
36
+ client = new Client({ url }).setAdapter(GraphqlAdapter());
37
+ fetchSpy = vi.spyOn(globalThis, "fetch");
38
+ });
39
+
40
+ afterEach(() => {
41
+ fetchSpy.mockRestore();
42
+ vi.unstubAllGlobals();
43
+ });
44
+
45
+ it("should send the full query when persisted queries are off", async () => {
46
+ fetchSpy.mockResolvedValueOnce(json(user));
47
+
48
+ await client.createRequest<{ response: UserResponse }>()({ endpoint: query }).send();
49
+
50
+ expect(sentBody(0)).toEqual({ query, operationName: "GetUser" });
51
+ });
52
+
53
+ it("should send only the hash when the server knows the query", async () => {
54
+ fetchSpy.mockResolvedValueOnce(json(user));
55
+
56
+ const response = await createRequest().send();
57
+
58
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
59
+ expect(sentBody(0)).toEqual({ operationName: "GetUser", extensions: { persistedQuery } });
60
+ expect(response).toMatchObject({ data: user.data, error: null, success: true });
61
+ });
62
+
63
+ it.each([
64
+ ["the message", notFound],
65
+ ["the error code", { errors: [{ message: "Not found", extensions: { code: "PERSISTED_QUERY_NOT_FOUND" } }] }],
66
+ ])("should register the query when the server reports by %s that it does not know it", async (_name, miss) => {
67
+ fetchSpy.mockResolvedValueOnce(json(miss)).mockResolvedValueOnce(json(user));
68
+
69
+ const response = await createRequest().send();
70
+
71
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
72
+ expect(sentBody(1)).toEqual({ query, operationName: "GetUser", extensions: { persistedQuery } });
73
+ expect(response).toMatchObject({ data: user.data, error: null, success: true });
74
+ });
75
+
76
+ it("should register the query after a miss reported with a failed status", async () => {
77
+ fetchSpy.mockResolvedValueOnce(json(notFound, 400)).mockResolvedValueOnce(json(user));
78
+
79
+ const response = await createRequest().send();
80
+
81
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
82
+ expect(response).toMatchObject({ data: user.data, success: true, status: 200 });
83
+ });
84
+
85
+ it("should send full queries after the server reports it does not support persisted queries", async () => {
86
+ fetchSpy
87
+ .mockResolvedValueOnce(json(notSupported))
88
+ .mockResolvedValueOnce(json(user))
89
+ .mockResolvedValueOnce(json(user));
90
+
91
+ const first = await createRequest().send();
92
+ const second = await createRequest().send();
93
+
94
+ expect(first).toMatchObject({ data: user.data, success: true });
95
+ expect(second).toMatchObject({ data: user.data, success: true });
96
+ expect(fetchSpy).toHaveBeenCalledTimes(3);
97
+ expect(sentBody(1)).toEqual({ query, operationName: "GetUser" });
98
+ expect(sentBody(2)).toEqual({ query, operationName: "GetUser" });
99
+ });
100
+
101
+ it("should not retry other errors", async () => {
102
+ fetchSpy.mockResolvedValueOnce(json({ errors: [{ message: "Not allowed" }] }));
103
+
104
+ const response = await createRequest().send();
105
+
106
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
107
+ expect(response).toMatchObject({ data: null, error: [{ message: "Not allowed" }], success: false });
108
+ });
109
+
110
+ it("should return the error of the registering request", async () => {
111
+ fetchSpy.mockResolvedValueOnce(json(notFound)).mockResolvedValueOnce(json({ errors: [{ message: "Invalid" }] }));
112
+
113
+ const response = await createRequest().send();
114
+
115
+ expect(response).toMatchObject({ data: null, error: [{ message: "Invalid" }], success: false });
116
+ });
117
+
118
+ it("should send the hash without the query in the url of a GET request", async () => {
119
+ fetchSpy.mockResolvedValueOnce(json(user));
120
+
121
+ await createRequest(GraphqlMethod.GET).send();
122
+
123
+ const params = sentParams(0);
124
+ expect(params.has("query")).toBeFalse();
125
+ expect(params.get("operationName")).toBe("GetUser");
126
+ expect(JSON.parse(params.get("extensions") ?? "")).toEqual({ persistedQuery });
127
+ expect(fetchSpy.mock.calls[0][1]?.body).toBeUndefined();
128
+ });
129
+
130
+ it("should keep the extensions of the GET url over a query param with the same key", async () => {
131
+ fetchSpy.mockResolvedValueOnce(json(user));
132
+ const request = client
133
+ .createRequest<{ response: UserResponse; queryParams: { extensions: string } }>()({
134
+ endpoint: query,
135
+ method: GraphqlMethod.GET,
136
+ options: { persistedQueries: true },
137
+ })
138
+ .setQueryParams({ extensions: "other" });
139
+
140
+ await request.send();
141
+
142
+ expect(sentParams(0).getAll("extensions")).toStrictEqual([JSON.stringify({ persistedQuery })]);
143
+ });
144
+
145
+ it("should register a GET query in the url", async () => {
146
+ fetchSpy.mockResolvedValueOnce(json(notFound)).mockResolvedValueOnce(json(user));
147
+
148
+ await createRequest(GraphqlMethod.GET).send();
149
+
150
+ const params = sentParams(1);
151
+ expect(params.get("query")).toBe(query);
152
+ expect(JSON.parse(params.get("extensions") ?? "")).toEqual({ persistedQuery });
153
+ });
154
+
155
+ it("should send the full query when the runtime has no Web Crypto", async () => {
156
+ // Insecure contexts expose crypto without subtle
157
+ vi.stubGlobal("crypto", {});
158
+ fetchSpy.mockResolvedValueOnce(json(user));
159
+
160
+ const response = await createRequest().send();
161
+
162
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
163
+ expect(sentBody(0)).toEqual({ query, operationName: "GetUser" });
164
+ expect(response).toMatchObject({ data: user.data, success: true });
165
+ });
166
+
167
+ it("should take the option from the adapter defaults", async () => {
168
+ fetchSpy.mockResolvedValueOnce(json(user));
169
+ const defaulted = new Client({ url }).setAdapter(
170
+ GraphqlAdapter().setAdapterDefaults(() => ({ persistedQueries: true })),
171
+ );
172
+
173
+ await defaulted.createRequest<{ response: UserResponse }>()({ endpoint: query }).send();
174
+
175
+ expect(sentBody(0)).toEqual({ operationName: "GetUser", extensions: { persistedQuery } });
176
+ });
177
+
178
+ it("should time out a registering request that does not answer", async () => {
179
+ fetchSpy.mockResolvedValueOnce(json(notFound)).mockImplementationOnce(
180
+ (_input, init) =>
181
+ new Promise((_resolve, reject) => {
182
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
183
+ }),
184
+ );
185
+ const request = client.createRequest<{ response: UserResponse }>()({
186
+ endpoint: query,
187
+ options: { persistedQueries: true, timeout: 50 },
188
+ });
189
+
190
+ const response = await request.send();
191
+
192
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
193
+ expect(response).toMatchObject({ data: null, success: false, status: 0 });
194
+ expect(response.error).toHaveLength(1);
195
+ });
196
+
197
+ it("should report the progress of the response once for a hashed request", async () => {
198
+ fetchSpy.mockResolvedValueOnce(json(user));
199
+ const onProgress = vi.fn();
200
+
201
+ await createRequest().send({ onDownloadProgress: onProgress });
202
+
203
+ const progress = onProgress.mock.calls.map(([event]) => event.loaded);
204
+ expect(progress.length).toBeGreaterThan(0);
205
+ expect(progress.every((value, index) => index === 0 || value >= progress[index - 1])).toBeTrue();
206
+ });
207
+ });