@hyper-fetch/graphql 9.3.0 → 9.4.1

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.
@@ -18,6 +18,7 @@ export type GraphQLServerOptions = {
18
18
  export const createE2EGraphQLServer = (options: GraphQLServerOptions) => {
19
19
  let server: http.Server | null = null;
20
20
  let port = 0;
21
+ let lastRequestUrl = "";
21
22
 
22
23
  const schema: GraphQLSchema = buildSchema(options.typeDefs);
23
24
  const rootValue = options.resolvers;
@@ -33,6 +34,7 @@ export const createE2EGraphQLServer = (options: GraphQLServerOptions) => {
33
34
  };
34
35
 
35
36
  const handleRequest = async (req: http.IncomingMessage, res: http.ServerResponse) => {
37
+ lastRequestUrl = req.url || "";
36
38
  res.setHeader("Access-Control-Allow-Origin", "*");
37
39
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
38
40
 
@@ -131,5 +133,7 @@ export const createE2EGraphQLServer = (options: GraphQLServerOptions) => {
131
133
 
132
134
  const getUrl = () => `http://127.0.0.1:${port}`;
133
135
 
134
- return { startServer, stopServer, getUrl };
136
+ const getLastRequestUrl = () => lastRequestUrl;
137
+
138
+ return { startServer, stopServer, getUrl, getLastRequestUrl };
135
139
  };
@@ -76,7 +76,7 @@ type GqlResponse<T> = { response: T; error: { message: string }[] };
76
76
 
77
77
  // ─── Server Setup ────────────────────────────────────────────────────
78
78
 
79
- const { startServer, stopServer } = createE2EGraphQLServer({ typeDefs, resolvers });
79
+ const { startServer, stopServer, getLastRequestUrl } = createE2EGraphQLServer({ typeDefs, resolvers });
80
80
 
81
81
  let baseUrl: string;
82
82
 
@@ -484,3 +484,64 @@ describe("E2E GraphQL [ Multiple Operations ]", () => {
484
484
  expect(result2.data!.user.username).toBe("jane");
485
485
  });
486
486
  });
487
+
488
+ describe("E2E GraphQL [ Document and query params ]", () => {
489
+ const USER_QUERY = "query User($id: ID!) { user(id: $id) { id username } }";
490
+ type UserResponse = GqlResponse<{ user: { id: string; username: string } }> & {
491
+ payload: { id: string };
492
+ };
493
+
494
+ it("should send POST to the path with query params and the variables in the body", async () => {
495
+ const client = new Client({ url: `${baseUrl}/graphql` }).setAdapter(GraphqlAdapter());
496
+ const request = client.createRequest<UserResponse>()({ endpoint: "/User", document: USER_QUERY });
497
+
498
+ const { data, error } = await request
499
+ .setQueryParams({ source: "app", build: "1.2.3" })
500
+ .send({ payload: { id: "1" } });
501
+
502
+ expect(error).toBeNull();
503
+ expect(data).toStrictEqual({ user: { id: "1", username: "john" } });
504
+ expect(getLastRequestUrl()).toBe("/graphql/User?source=app&build=1.2.3");
505
+ });
506
+
507
+ it("should send GET to the path with everything in the query string", async () => {
508
+ const client = new Client({ url: `${baseUrl}/graphql` }).setAdapter(GraphqlAdapter());
509
+ const request = client.createRequest<UserResponse>()({
510
+ endpoint: "/User",
511
+ document: USER_QUERY,
512
+ method: GraphqlMethod.GET,
513
+ });
514
+
515
+ const { data, error } = await request
516
+ .setQueryParams({ source: "app", query: "ignored", variables: "ignored" })
517
+ .send({ payload: { id: "2" } });
518
+
519
+ expect(error).toBeNull();
520
+ expect(data).toStrictEqual({ user: { id: "2", username: "jane" } });
521
+
522
+ const { pathname, searchParams } = new URL(getLastRequestUrl(), baseUrl);
523
+ expect(pathname).toBe("/graphql/User");
524
+ expect(searchParams.get("source")).toBe("app");
525
+ expect(searchParams.getAll("query")).toStrictEqual([USER_QUERY]);
526
+ expect(searchParams.getAll("variables")).toStrictEqual([JSON.stringify({ id: "2" })]);
527
+ });
528
+
529
+ it("should keep the client url when document is omitted", async () => {
530
+ const client = new Client({ url: `${baseUrl}/graphql` }).setAdapter(GraphqlAdapter());
531
+ const request = client.createRequest<UserResponse>()({ endpoint: USER_QUERY });
532
+
533
+ const { data } = await request.send({ payload: { id: "1" } } as any);
534
+
535
+ expect(data).toStrictEqual({ user: { id: "1", username: "john" } });
536
+ expect(getLastRequestUrl()).toBe("/graphql");
537
+ });
538
+
539
+ it("should apply query params when document is omitted", async () => {
540
+ const client = new Client({ url: `${baseUrl}/graphql` }).setAdapter(GraphqlAdapter());
541
+ const request = client.createRequest<UserResponse>()({ endpoint: USER_QUERY });
542
+
543
+ await request.setQueryParams({ source: "app" }).send({ payload: { id: "1" } } as any);
544
+
545
+ expect(getLastRequestUrl()).toBe("/graphql?source=app");
546
+ });
547
+ });
@@ -256,4 +256,107 @@ describe("Graphql Adapter [ Browser ]", () => {
256
256
 
257
257
  global.fetch = originalFetch;
258
258
  });
259
+
260
+ describe("when using the document option", () => {
261
+ const getFetchUrl = (spy: { mock: { calls: unknown[][] } }) => String(spy.mock.calls[0][0]);
262
+
263
+ it("should send the request to the path of the operation", async () => {
264
+ const operation = client.createRequest<{ response: GetUserQueryResponse }>()({
265
+ endpoint: "/User",
266
+ document: getUserQuery,
267
+ });
268
+ const expected = mockRequest(operation, { data: { username: "prc", firstName: "Maciej" } });
269
+ const spy = vi.spyOn(globalThis, "fetch");
270
+
271
+ const { data, error, status } = await operation.setQueryParams({ source: "app", build: "1.2.3" }).send();
272
+
273
+ expect(expected.data).toStrictEqual(data);
274
+ expect(error).toBe(null);
275
+ expect(status).toBe(200);
276
+ expect(getFetchUrl(spy)).toBe("https://shared-base-url/graphql/User?source=app&build=1.2.3");
277
+ });
278
+
279
+ it("should not reach the handler of a different path", async () => {
280
+ const operation = client.createRequest<{ response: GetUserQueryResponse }>()({
281
+ endpoint: "/User",
282
+ document: getUserQuery,
283
+ });
284
+ const other = client.createRequest<{ response: GetUserQueryResponse }>()({
285
+ endpoint: "/Other",
286
+ document: getUserQuery,
287
+ });
288
+ mockRequest(other, { data: { username: "other", firstName: "Other" } });
289
+ const expected = mockRequest(operation, { data: { username: "prc", firstName: "Maciej" } });
290
+
291
+ const { data } = await operation.send();
292
+
293
+ expect(data).toStrictEqual(expected.data);
294
+ });
295
+
296
+ it("should send mutations", async () => {
297
+ const operation = client.createRequest<{ response: GetUserQueryResponse; payload: LoginMutationVariables }>()({
298
+ endpoint: "/Login",
299
+ document: loginMutation,
300
+ });
301
+ const expected = mockRequest(operation, { data: { username: "prc", firstName: "Maciej" } });
302
+
303
+ const { data, error } = await operation.send({ payload: { username: "Kacper", password: "Kacper1234" } });
304
+
305
+ expect(expected.data).toStrictEqual(data);
306
+ expect(error).toBe(null);
307
+ });
308
+
309
+ it("should run parallel requests against different paths without changing the client url", async () => {
310
+ const first = client.createRequest<{ response: GetUserQueryResponse }>()({
311
+ endpoint: "/First",
312
+ document: getUserQuery,
313
+ });
314
+ const second = client.createRequest<{ response: GetUserQueryResponse }>()({
315
+ endpoint: "/Second",
316
+ document: getUserQuery,
317
+ });
318
+ const firstExpected = mockRequest(first, { data: { username: "first", firstName: "First" } });
319
+ const secondExpected = mockRequest(second, { data: { username: "second", firstName: "Second" } });
320
+
321
+ const [firstResponse, secondResponse] = await Promise.all([first.send(), second.send()]);
322
+
323
+ expect(firstResponse.data).toStrictEqual(firstExpected.data);
324
+ expect(secondResponse.data).toStrictEqual(secondExpected.data);
325
+ expect(client.url).toBe("https://shared-base-url/graphql");
326
+ });
327
+
328
+ it("should not share the cache between paths", async () => {
329
+ const cacheClient = new Client({ url: "https://shared-base-url/graphql", mode: "client" }).setAdapter(
330
+ GraphqlAdapter(),
331
+ );
332
+ const first = cacheClient.createRequest<{ response: GetUserQueryResponse }>()({
333
+ endpoint: "/First",
334
+ document: getUserQuery,
335
+ });
336
+ const second = cacheClient.createRequest<{ response: GetUserQueryResponse }>()({
337
+ endpoint: "/Second",
338
+ document: getUserQuery,
339
+ });
340
+ const firstExpected = mockRequest(first, { data: { username: "first", firstName: "First" } });
341
+ const secondExpected = mockRequest(second, { data: { username: "second", firstName: "Second" } });
342
+
343
+ await first.send();
344
+ await second.send();
345
+
346
+ expect(first.read()?.data).toStrictEqual(firstExpected.data);
347
+ expect(second.read()?.data).toStrictEqual(secondExpected.data);
348
+ });
349
+ });
350
+
351
+ describe("when using query params without the document option", () => {
352
+ it("should append them to the client url", async () => {
353
+ const expected = mockRequest(request, { data: { username: "prc", firstName: "Maciej" } });
354
+ const spy = vi.spyOn(globalThis, "fetch");
355
+
356
+ const { data } = await request.setQueryParams({ source: "app" }).send();
357
+
358
+ expect(expected.data).toStrictEqual(data);
359
+ expect(String(spy.mock.calls[0][0])).toBe("https://shared-base-url/graphql?source=app");
360
+ });
361
+ });
259
362
  });
@@ -0,0 +1,383 @@
1
+ import { Client, stringifyDefaultOptions } from "@hyper-fetch/core";
2
+ import { GraphqlAdapter, GraphqlMethod, getGqlDocument, getRequestValues, gqlEndpointNameMapper } from "adapter";
3
+ import gql from "graphql-tag";
4
+
5
+ import { getUserQuery, getUserQueryString } from "../../constants/queries.constants";
6
+
7
+ const url = "https://shared-base-url/graphql";
8
+ const printedQuery = "query GetUser {\n username {\n username\n firstName\n }\n}";
9
+
10
+ const getQueryString = (fullUrl: string) => new URL(fullUrl).searchParams;
11
+
12
+ describe("Graphql Adapter [ Document and query params ]", () => {
13
+ const createClient = () => new Client({ url }).setAdapter(GraphqlAdapter());
14
+
15
+ let client = createClient();
16
+
17
+ beforeEach(() => {
18
+ client = createClient();
19
+ });
20
+
21
+ describe("When document is omitted", () => {
22
+ it("should keep the endpoint as the document and the client url as the url", () => {
23
+ const request = client.createRequest()({ endpoint: getUserQuery });
24
+
25
+ const { fullUrl, payload } = getRequestValues(request);
26
+
27
+ expect(fullUrl).toBe(url);
28
+ expect(payload).toBe(JSON.stringify({ query: printedQuery }));
29
+ expect(getGqlDocument(request)).toBe(printedQuery);
30
+ });
31
+
32
+ it("should keep the same keys as before", () => {
33
+ const request = client.createRequest()({ endpoint: getUserQueryString });
34
+
35
+ expect(request.cacheKey).toBe("POST_GetUser--");
36
+ expect(request.queryKey).toBe("POST_GetUser--");
37
+ expect(request.abortKey).toBe("POST_GetUser-false");
38
+ });
39
+
40
+ it("should append query params to the POST url", () => {
41
+ const request = client
42
+ .createRequest<{ queryParams: { source: string } }>()({ endpoint: getUserQuery })
43
+ .setQueryParams({ source: "app" });
44
+
45
+ const { fullUrl, payload } = getRequestValues(request);
46
+
47
+ expect(fullUrl).toBe(`${url}?source=app`);
48
+ expect(payload).toBe(JSON.stringify({ query: printedQuery }));
49
+ });
50
+
51
+ it("should merge query params into the GET query string", () => {
52
+ const request = client
53
+ .createRequest<{ queryParams: { source: string } }>()({ endpoint: getUserQuery, method: GraphqlMethod.GET })
54
+ .setQueryParams({ source: "app" });
55
+
56
+ const { fullUrl, payload } = getRequestValues(request);
57
+
58
+ expect(fullUrl.startsWith(`${url}?query=`)).toBeTrue();
59
+ expect(getQueryString(fullUrl).get("query")).toBe(printedQuery);
60
+ expect(getQueryString(fullUrl).get("source")).toBe("app");
61
+ expect(payload).toBeNull();
62
+ });
63
+ });
64
+
65
+ describe("When document is set", () => {
66
+ it("should use the endpoint as the url path and print the DocumentNode as query", () => {
67
+ const request = client.createRequest()({ endpoint: "/User", document: getUserQuery });
68
+
69
+ const { fullUrl, payload } = getRequestValues(request);
70
+
71
+ expect(fullUrl).toBe(`${url}/User`);
72
+ expect(payload).toBe(JSON.stringify({ query: printedQuery }));
73
+ expect(request.endpoint).toBe("/User");
74
+ expect(getGqlDocument(request)).toBe(getUserQuery);
75
+ });
76
+
77
+ it("should send a string document as it is", () => {
78
+ const request = client.createRequest()({ endpoint: "/User", document: getUserQueryString });
79
+
80
+ expect(getRequestValues(request).payload).toBe(JSON.stringify({ query: getUserQueryString }));
81
+ });
82
+
83
+ it("should build the url from the issue example", () => {
84
+ const request = client
85
+ .createRequest<{ payload: { id: number } }>()({ endpoint: "/User", document: getUserQuery })
86
+ .setQueryParams({ source: "app", build: "1.2.3" })
87
+ .setPayload({ id: 1 });
88
+
89
+ const { fullUrl, payload } = getRequestValues(request);
90
+
91
+ expect(fullUrl).toBe(`${url}/User?source=app&build=1.2.3`);
92
+ expect(payload).toBe(JSON.stringify({ query: printedQuery, variables: { id: 1 } }));
93
+ });
94
+
95
+ it("should send everything in the query string for GET", () => {
96
+ const request = client
97
+ .createRequest<{ payload: { id: number } }>()({
98
+ endpoint: "/User",
99
+ document: getUserQuery,
100
+ method: GraphqlMethod.GET,
101
+ })
102
+ .setQueryParams({ source: "app" })
103
+ .setPayload({ id: 1 });
104
+
105
+ const { fullUrl, payload } = getRequestValues(request);
106
+ const searchParams = getQueryString(fullUrl);
107
+
108
+ expect(fullUrl.startsWith(`${url}/User?query=`)).toBeTrue();
109
+ expect(searchParams.get("query")).toBe(printedQuery);
110
+ expect(searchParams.get("variables")).toBe(JSON.stringify({ id: 1 }));
111
+ expect(searchParams.get("source")).toBe("app");
112
+ expect(payload).toBeNull();
113
+ });
114
+
115
+ it("should allow for an empty path", () => {
116
+ const request = client
117
+ .createRequest()({ endpoint: "", document: getUserQuery })
118
+ .setQueryParams({ source: "app" });
119
+
120
+ expect(getRequestValues(request).fullUrl).toBe(`${url}?source=app`);
121
+ });
122
+
123
+ it("should replace params in the url path", () => {
124
+ const request = client.createRequest()({ endpoint: "/tenant/:tenantId/User", document: getUserQuery });
125
+
126
+ const { fullUrl, payload } = getRequestValues(request.setParams({ tenantId: 7 }));
127
+
128
+ expect(fullUrl).toBe(`${url}/tenant/7/User`);
129
+ expect(payload).toBe(JSON.stringify({ query: printedQuery }));
130
+ });
131
+
132
+ it("should treat nullish document as omitted", () => {
133
+ const request = client.createRequest()({ endpoint: getUserQueryString, document: undefined });
134
+
135
+ expect(getRequestValues(request).fullUrl).toBe(url);
136
+ expect(getGqlDocument(request)).toBe(getUserQueryString);
137
+ });
138
+
139
+ it("should keep the document on clones", () => {
140
+ const request = client.createRequest()({ endpoint: "/User", document: getUserQuery });
141
+
142
+ const cloned = request.setHeaders({ a: "b" }).setRetry(1).clone();
143
+
144
+ expect(getRequestValues(cloned).fullUrl).toBe(`${url}/User`);
145
+ expect(getGqlDocument(cloned)).toBe(getUserQuery);
146
+ });
147
+
148
+ it("should survive JSON serialization", () => {
149
+ const request = client.createRequest()({ endpoint: "/User", document: getUserQuery });
150
+
151
+ const restored = JSON.parse(JSON.stringify(request.toJSON()));
152
+ const hydrated = client.fromJSON(restored);
153
+
154
+ expect(getRequestValues(hydrated as any).fullUrl).toBe(`${url}/User`);
155
+ expect(getRequestValues(hydrated as any).payload).toBe(JSON.stringify({ query: printedQuery }));
156
+ expect(hydrated.cacheKey).toBe(request.cacheKey);
157
+ });
158
+ });
159
+
160
+ describe("When mapping query params", () => {
161
+ const getUrl = (queryParams: any, method = GraphqlMethod.POST) => {
162
+ const request = client.createRequest<{ queryParams: any }>()({ endpoint: "/User", document: "{ a }", method });
163
+ return getRequestValues(request.setQueryParams(queryParams)).fullUrl;
164
+ };
165
+
166
+ it("should not add a question mark without query params", () => {
167
+ expect(getUrl(undefined)).toBe(`${url}/User`);
168
+ expect(getUrl(null)).toBe(`${url}/User`);
169
+ expect(getUrl({})).toBe(`${url}/User`);
170
+ expect(getUrl("")).toBe(`${url}/User`);
171
+ expect(getUrl("?")).toBe(`${url}/User`);
172
+ });
173
+
174
+ it("should accept string query params with and without the question mark", () => {
175
+ expect(getUrl("a=1&b=2")).toBe(`${url}/User?a=1&b=2`);
176
+ expect(getUrl("?a=1&b=2")).toBe(`${url}/User?a=1&b=2`);
177
+ });
178
+
179
+ it("should encode values and skip the empty ones", () => {
180
+ expect(getUrl({ a: "x y", b: undefined, c: null, d: [1, 2] })).toBe(`${url}/User?a=x%20y&d[]=1&d[]=2`);
181
+ });
182
+
183
+ it("should leave query and variables keys alone for POST", () => {
184
+ expect(getUrl({ query: "mine", variables: "mine" })).toBe(`${url}/User?query=mine&variables=mine`);
185
+ });
186
+
187
+ it.each([
188
+ ["object", { query: "mine", variables: "mine", source: "app" }],
189
+ ["string", "query=mine&variables=mine&source=app"],
190
+ ["string with question mark", "?variables=mine&query=mine&source=app"],
191
+ ["encoded keys", "%71uery=mine&source=app"],
192
+ ["array", { query: ["mine", "mine2"], source: "app" }],
193
+ ["bracket array", "query[]=mine&query%5B%5D=mine2&variables[0]=mine&source=app"],
194
+ ])("should prefer query and variables on GET collision for %s", (_, queryParams) => {
195
+ const request = client
196
+ .createRequest<{ queryParams: any; payload: any }>()({
197
+ endpoint: "/User",
198
+ document: "{ a }",
199
+ method: GraphqlMethod.GET,
200
+ })
201
+ .setQueryParams(queryParams)
202
+ .setPayload({ id: 1 });
203
+
204
+ const searchParams = getQueryString(getRequestValues(request).fullUrl);
205
+
206
+ expect(searchParams.getAll("query")).toStrictEqual(["{ a }"]);
207
+ expect(searchParams.getAll("variables")).toStrictEqual([JSON.stringify({ id: 1 })]);
208
+ expect(searchParams.get("source")).toBe("app");
209
+ expect([...searchParams.keys()]).toStrictEqual(["query", "variables", "source"]);
210
+ });
211
+
212
+ it("should not fail on malformed keys", () => {
213
+ expect(getUrl("%ZZ=1&a=2", GraphqlMethod.GET)).toEndWith("&%ZZ=1&a=2");
214
+ });
215
+
216
+ it("should keep similarly named keys on GET", () => {
217
+ const searchParams = getQueryString(getUrl({ queryId: 1, "variables.a": 2 }, GraphqlMethod.GET));
218
+
219
+ expect(searchParams.get("queryId")).toBe("1");
220
+ expect(searchParams.get("variables.a")).toBe("2");
221
+ });
222
+
223
+ it("should use the custom query params mapper", () => {
224
+ const mapper = vi.fn((queryParams: any) => `custom=${queryParams.a}`);
225
+ const customClient = new Client({ url }).setAdapter(GraphqlAdapter().setQueryParamsMapper(mapper));
226
+ const request = customClient
227
+ .createRequest<{ queryParams: { a: number } }>()({ endpoint: "/User", document: "{ a }" })
228
+ .setQueryParams({ a: 1 });
229
+
230
+ expect(getRequestValues(request).fullUrl).toBe(`${url}/User?custom=1`);
231
+ expect(mapper).toHaveBeenCalledWith({ a: 1 }, undefined);
232
+ });
233
+
234
+ it("should accept the object returned from the custom mapper", () => {
235
+ const customClient = new Client({ url }).setAdapter(
236
+ GraphqlAdapter().setQueryParamsMapper((queryParams) => ({ ...(queryParams as any), mapped: true })),
237
+ );
238
+ const request = customClient
239
+ .createRequest<{ queryParams: { a: number } }>()({ endpoint: "/User", document: "{ a }" })
240
+ .setQueryParams({ a: 1 });
241
+
242
+ expect(getRequestValues(request).fullUrl).toBe(`${url}/User?a=1&mapped=true`);
243
+ });
244
+
245
+ it("should use the query params mapper config", () => {
246
+ const customClient = new Client({ url }).setAdapter(
247
+ GraphqlAdapter().setQueryParamsMapperConfig({ arrayFormat: "bracket" }),
248
+ );
249
+ const request = customClient
250
+ .createRequest<{ queryParams: { a: number[] } }>()({ endpoint: "/User", document: "{ a }" })
251
+ .setQueryParams({ a: [1, 2] });
252
+
253
+ expect(getRequestValues(request).fullUrl).toBe(`${url}/User?a[]=1&a[]=2`);
254
+ });
255
+
256
+ it("should keep the encoding with the default options spread into the config", () => {
257
+ const customClient = new Client({ url }).setAdapter(
258
+ GraphqlAdapter().setQueryParamsMapperConfig({ ...stringifyDefaultOptions, arrayFormat: "comma" }),
259
+ );
260
+ const request = customClient
261
+ .createRequest<{ queryParams: { a: string[] } }>()({ endpoint: "/User", document: "{ a }" })
262
+ .setQueryParams({ a: ["x y", "z"] });
263
+
264
+ expect(getRequestValues(request).fullUrl).toBe(`${url}/User?a=x%20y,z`);
265
+ });
266
+
267
+ it("should prefer already mapped query params passed by the fetcher", () => {
268
+ const mapper = vi.fn(() => "from=mapper");
269
+ const customClient = new Client({ url }).setAdapter(GraphqlAdapter().setQueryParamsMapper(mapper));
270
+ const request = customClient.createRequest()({ endpoint: "/User", document: "{ a }" });
271
+
272
+ expect(getRequestValues(request, "from=bindings").fullUrl).toBe(`${url}/User?from=bindings`);
273
+ expect(mapper).not.toHaveBeenCalled();
274
+ });
275
+ });
276
+
277
+ describe("When generating keys", () => {
278
+ it("should read the operation name from the document", () => {
279
+ const fromNode = client.createRequest()({ endpoint: "/User", document: getUserQuery });
280
+ const fromString = client.createRequest()({ endpoint: "/User", document: getUserQueryString });
281
+
282
+ [fromNode, fromString].forEach((request) => {
283
+ expect(request.cacheKey).toBe("POST_GetUser/User--");
284
+ expect(request.queryKey).toBe("POST_GetUser/User--");
285
+ expect(request.abortKey).toBe("POST_GetUser/User-false");
286
+ });
287
+ });
288
+
289
+ it("should not add the path for the empty endpoint", () => {
290
+ const request = client.createRequest()({ endpoint: "", document: getUserQuery });
291
+
292
+ expect(request.cacheKey).toBe("POST_GetUser--");
293
+ });
294
+
295
+ it("should distinguish the same operation sent to different paths", () => {
296
+ const v1 = client.createRequest()({ endpoint: "/v1/User", document: getUserQuery });
297
+ const v2 = client.createRequest()({ endpoint: "/v2/User", document: getUserQuery });
298
+
299
+ expect(v1.cacheKey).not.toBe(v2.cacheKey);
300
+ expect(v1.queryKey).not.toBe(v2.queryKey);
301
+ expect(v1.abortKey).not.toBe(v2.abortKey);
302
+ });
303
+
304
+ it("should distinguish different operations sent to the same path", () => {
305
+ const first = client.createRequest()({ endpoint: "/graphql", document: "query First { a }" });
306
+ const second = client.createRequest()({ endpoint: "/graphql", document: "query Second { a }" });
307
+
308
+ expect(first.cacheKey).not.toBe(second.cacheKey);
309
+ });
310
+
311
+ it("should include query params and params in the cache and query keys", () => {
312
+ const request = client.createRequest()({ endpoint: "/tenant/:id/User", document: getUserQuery });
313
+
314
+ const withQuery = request.setQueryParams({ a: 1 });
315
+ const withParams = request.setParams({ id: 2 });
316
+
317
+ expect(withQuery.cacheKey).not.toBe(request.cacheKey);
318
+ expect(withQuery.queryKey).not.toBe(request.queryKey);
319
+ expect(withParams.cacheKey).not.toBe(request.cacheKey);
320
+ expect(withParams.queryKey).not.toBe(request.queryKey);
321
+ // Every value of the params shares one abort group, same as in the HttpAdapter
322
+ expect(withParams.abortKey).toBe(request.abortKey);
323
+ });
324
+
325
+ it("should keep the explicit keys", () => {
326
+ const request = client.createRequest()({ endpoint: "/User", document: getUserQuery, cacheKey: "mine" });
327
+
328
+ expect(request.cacheKey).toBe("mine");
329
+ });
330
+ });
331
+
332
+ describe("When using gqlEndpointNameMapper", () => {
333
+ it("should read the name from a DocumentNode", () => {
334
+ expect(gqlEndpointNameMapper(getUserQuery)).toBe("GetUser");
335
+ });
336
+
337
+ it("should read the first field from an anonymous DocumentNode", () => {
338
+ expect(
339
+ gqlEndpointNameMapper(
340
+ gql`
341
+ {
342
+ username {
343
+ id
344
+ }
345
+ }
346
+ `,
347
+ ),
348
+ ).toBe("username");
349
+ });
350
+
351
+ it("should use the fallback for a DocumentNode without operation", () => {
352
+ expect(
353
+ gqlEndpointNameMapper(
354
+ gql`
355
+ fragment A on User {
356
+ id
357
+ }
358
+ `,
359
+ ),
360
+ ).toBe("graphql-request");
361
+ });
362
+
363
+ it("should use the name of the mutation", () => {
364
+ expect(gqlEndpointNameMapper("mutation Login($a: String!) { login(a: $a) { id } }")).toBe("Login");
365
+ });
366
+ });
367
+
368
+ describe("When using the devtools endpoint getter", () => {
369
+ const getter = () => client.adapter.unstable_devtoolsEndpointGetter;
370
+
371
+ it("should read the operation name from the endpoint", () => {
372
+ expect(getter()(getUserQueryString)).toBe("GetUser");
373
+ expect(getter()(getUserQueryString, { endpoint: getUserQueryString })).toBe("GetUser");
374
+ });
375
+
376
+ it("should read the operation name from the document", () => {
377
+ const request = client.createRequest()({ endpoint: "/User", document: getUserQuery });
378
+
379
+ expect(getter()("/User", request.requestOptions)).toBe("GetUser");
380
+ expect(getter()("/User", { document: getUserQueryString })).toBe("GetUser");
381
+ });
382
+ });
383
+ });
@@ -0,0 +1,115 @@
1
+ import type { ClientInstance, ExtractAdapterRequestOptionsType, RequestInstance } from "@hyper-fetch/core";
2
+ import { Client, HttpAdapter } from "@hyper-fetch/core";
3
+ import type { ExtractGqlRouteParams, GraphqlAdapterType, GraphqlRequestOptionsType } from "adapter";
4
+ import { GraphqlAdapter } from "adapter";
5
+ import type { DocumentNode } from "graphql";
6
+ import { expectTypeOf } from "vitest";
7
+
8
+ import { getUserQuery } from "../../constants/queries.constants";
9
+
10
+ type UserResponse = { username: string };
11
+
12
+ describe("Graphql Adapter [ Types ]", () => {
13
+ const client = new Client({ url: "https://shared-base-url/graphql" }).setAdapter(GraphqlAdapter());
14
+
15
+ it("should expose document in the adapter request options", () => {
16
+ expectTypeOf<ExtractAdapterRequestOptionsType<GraphqlAdapterType>>().toEqualTypeOf<GraphqlRequestOptionsType>();
17
+ expectTypeOf<GraphqlRequestOptionsType["document"]>().toEqualTypeOf<string | DocumentNode | undefined>();
18
+ });
19
+
20
+ it("should accept string and DocumentNode documents", () => {
21
+ client.createRequest()({ endpoint: "/User", document: getUserQuery });
22
+ client.createRequest()({ endpoint: "/User", document: "query User { id }" });
23
+ client.createRequest()({ endpoint: "query User { id }" });
24
+ client.createRequest()({ endpoint: getUserQuery });
25
+
26
+ expectTypeOf(client.createRequest()).parameter(0).toHaveProperty("document");
27
+ // @ts-expect-error document has to be a string or a DocumentNode
28
+ expectTypeOf(client.createRequest()).parameter(0).toEqualTypeOf<{ endpoint: string; document: number }>();
29
+ });
30
+
31
+ it("should compile the example from the proposal", () => {
32
+ const getUser = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
33
+ endpoint: "/User",
34
+ document: getUserQuery,
35
+ });
36
+
37
+ const send = () => getUser.setQueryParams({ source: "app", build: "1.2.3" }).send({ payload: { id: 1 } });
38
+
39
+ expectTypeOf<Awaited<ReturnType<typeof send>>["data"]>().toEqualTypeOf<UserResponse | null>();
40
+ });
41
+
42
+ it("should not require query params when they are not declared", () => {
43
+ const request = client.createRequest<{ response: UserResponse }>()({ endpoint: "/User", document: getUserQuery });
44
+
45
+ expectTypeOf(request.send).toBeCallableWith();
46
+ expectTypeOf(request.send).toBeCallableWith({});
47
+ request.setQueryParams("source=app");
48
+ request.setQueryParams({ source: "app" });
49
+ });
50
+
51
+ it("should use the declared query params", () => {
52
+ const request = client.createRequest<{ queryParams: { source: string } }>()({
53
+ endpoint: "/User",
54
+ document: getUserQuery,
55
+ });
56
+
57
+ request.setQueryParams({ source: "app" });
58
+ // @ts-expect-error wrong query params
59
+ request.setQueryParams({ source: 1 });
60
+ });
61
+
62
+ it("should take the params from the url path when document is set", () => {
63
+ const request = client.createRequest()({ endpoint: "/tenant/:tenantId/User", document: getUserQuery });
64
+
65
+ request.setParams({ tenantId: 1 });
66
+ // @ts-expect-error unknown param
67
+ request.setParams({ other: 1 });
68
+ });
69
+
70
+ it("should keep the document after using adapter mapper setters", () => {
71
+ const adapter = GraphqlAdapter()
72
+ .setQueryParamsMapper(() => "a=1")
73
+ .setHeaderMapper(() => ({}))
74
+ .setPayloadMapper(() => "")
75
+ .setEndpointMapper(() => "/User");
76
+ const custom = new Client({ url: "" }).setAdapter(adapter);
77
+
78
+ custom.createRequest()({ endpoint: "/User", document: getUserQuery });
79
+
80
+ expectTypeOf<ExtractAdapterRequestOptionsType<typeof adapter>>().toEqualTypeOf<GraphqlRequestOptionsType>();
81
+ });
82
+
83
+ it("should not accept document for other adapters", () => {
84
+ const http = new Client({ url: "" }).setAdapter(HttpAdapter());
85
+
86
+ // @ts-expect-error document is declared only by the GraphqlAdapter
87
+ http.createRequest()({ endpoint: "/User", document: "query User { id }" });
88
+
89
+ expectTypeOf<ExtractAdapterRequestOptionsType<ReturnType<typeof HttpAdapter>>>().toEqualTypeOf<{}>();
90
+ });
91
+
92
+ it("should keep the params strict for not specified adapters", () => {
93
+ const create = (instance: ClientInstance) => {
94
+ // @ts-expect-error endpoint is required, the unknown adapter must not turn params into any
95
+ return instance.createRequest()({ document: "query User { id }" });
96
+ };
97
+
98
+ expectTypeOf(create).returns.toExtend<RequestInstance>();
99
+ });
100
+
101
+ it("should extract the variables from the document literal", () => {
102
+ const USER_QUERY = "query User($id: ID!, $name: String) { user(id: $id, name: $name) { id } }";
103
+
104
+ expectTypeOf<ExtractGqlRouteParams<typeof USER_QUERY>>().toMatchTypeOf<{ id: unknown; name?: unknown }>();
105
+
106
+ const request = client.createRequest<{ payload: ExtractGqlRouteParams<typeof USER_QUERY> }>()({
107
+ endpoint: "/User",
108
+ document: USER_QUERY,
109
+ });
110
+
111
+ request.setPayload({ id: 1 });
112
+ // @ts-expect-error id is required by the document
113
+ request.setPayload({ name: "a" });
114
+ });
115
+ });
@@ -1,4 +1,4 @@
1
- import { Adapter, EmptyTypes, QueryParamsType } from '@hyper-fetch/core';
1
+ import { Adapter, DefaultMapperType, EmptyTypes, QueryParamsType, stringifyQueryParams } from '@hyper-fetch/core';
2
2
  import { DocumentNode } from 'graphql/language/ast';
3
3
  export declare enum GraphqlMethod {
4
4
  POST = "POST",
@@ -12,7 +12,14 @@ export type GraphQlEndpointType = string | DocumentNode;
12
12
  export type FetchGraphqlAdapterOptionsType = Omit<RequestInit, "method" | "headers" | "body" | "signal"> & {
13
13
  timeout?: number;
14
14
  };
15
- export type GraphqlAdapterType = Adapter<FetchGraphqlAdapterOptionsType, GraphqlMethod, number, GraphQlExtraType, QueryParamsType | string, undefined, GraphQlEndpointType, (endpoint: GraphQlEndpointType) => string>;
15
+ export type GraphqlRequestOptionsType = {
16
+ /**
17
+ * GraphQL document sent as `query`. When it is set, `endpoint` becomes a URL path appended to `client.url`,
18
+ * the same way as in the HttpAdapter. When it is omitted, `endpoint` holds the document and the URL is `client.url`.
19
+ */
20
+ document?: GraphQlEndpointType;
21
+ };
22
+ export type GraphqlAdapterType = Adapter<FetchGraphqlAdapterOptionsType, GraphqlMethod, number, GraphQlExtraType, QueryParamsType | string, QueryParamsType | string | undefined, GraphQlEndpointType, (endpoint: GraphQlEndpointType) => string, typeof stringifyQueryParams, DefaultMapperType, DefaultMapperType, GraphqlRequestOptionsType>;
16
23
  type GqlParamType = boolean | string | number | Record<string, any> | EmptyTypes;
17
24
  export type ExtractGqlRouteParams<T extends string> = string extends T ? EmptyTypes : T extends `${string}query ${infer Parameters} {${infer QueryRest}` ? Parameters extends `${string}$${infer Param},${infer Rest}` ? GqlParameter<Param, Rest> & (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>) : Parameters extends `${string}$${infer Param})${infer Rest}` ? GqlParameter<Param, Rest> & (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>) : EmptyTypes : T extends `${string}$${infer Parameters},${infer Rest}` ? GqlParameter<Parameters, Rest> : T extends `${string}$${infer Parameters})${infer Rest}` ? GqlParameter<Parameters, Rest> : EmptyTypes;
18
25
  export type GqlParameter<T extends string, Rest extends string> = T extends `${infer Param}:${string}!` ? {
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.types.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC9E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,oBAAY,aAAa;IACvB,IAAI,SAAS;IACb,GAAG,QAAQ;CACZ;AAED,MAAM,MAAM,gBAAgB,GAAG;IAAE,OAAO,EAAE,WAAW,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAAE,CAAC;AAEzF,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,YAAY,CAAC;AAExD,MAAM,MAAM,8BAA8B,GAAG,IAAI,CAAC,WAAW,EAAE,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,CAAC,GAAG;IACzG,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,OAAO,CACtC,8BAA8B,EAC9B,aAAa,EACb,MAAM,EACN,gBAAgB,EAChB,eAAe,GAAG,MAAM,EACxB,SAAS,EACT,mBAAmB,EACnB,CAAC,QAAQ,EAAE,mBAAmB,KAAK,MAAM,CAC1C,CAAC;AAIF,KAAK,YAAY,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,UAAU,CAAC;AAEjF,MAAM,MAAM,qBAAqB,CAAC,CAAC,SAAS,MAAM,IAAI,MAAM,SAAS,CAAC,GAClE,UAAU,GACV,CAAC,SAAS,GAAG,MAAM,SAAS,MAAM,UAAU,KAAK,MAAM,SAAS,EAAE,GAChE,UAAU,SAAS,GAAG,MAAM,IAAI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"}
@@ -1,9 +1,16 @@
1
1
  import { RequestInstance } from '@hyper-fetch/core';
2
2
  import { GraphQlEndpointType } from './adapter.types';
3
- export declare const getRequestValues: <R extends RequestInstance>(request: R) => {
3
+ /** The document of the request - from the `document` option or, when it is omitted, from the `endpoint` */
4
+ export declare const getGqlDocument: (request: RequestInstance) => GraphQlEndpointType;
5
+ export declare const getRequestValues: <R extends RequestInstance>(request: R, queryParams?: unknown) => {
4
6
  fullUrl: string;
5
7
  payload: string | null;
6
8
  };
7
9
  export declare const gqlEndpointMapper: <E extends GraphQlEndpointType>(endpoint: E) => string;
8
- export declare const gqlEndpointNameMapper: (endpoint: string) => string;
10
+ export declare const gqlEndpointNameMapper: (endpoint: GraphQlEndpointType) => string;
11
+ /**
12
+ * Name identifying the request in the cache, query and abort keys.
13
+ * With the `document` option the same operation can be sent to many paths, so the path is a part of the name.
14
+ */
15
+ export declare const gqlRequestNameMapper: (request: RequestInstance) => string;
9
16
  //# sourceMappingURL=adapter.utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.utils.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKzD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3D,eAAO,MAAM,gBAAgB,GAAI,CAAC,SAAS,eAAe,EAAE,SAAS,CAAC;;;CAgBrE,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,mBAAmB,EAAE,UAAU,CAAC,KAAG,MAK9E,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,UAAU,MAAM,KAAG,MAgCxD,CAAC"}
1
+ {"version":3,"file":"adapter.utils.d.ts","sourceRoot":"","sources":["../../src/adapter/adapter.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA+B,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAKtF,OAAO,KAAK,EAAE,mBAAmB,EAA6B,MAAM,iBAAiB,CAAC;AAQtF,2GAA2G;AAC3G,eAAO,MAAM,cAAc,GAAI,SAAS,eAAe,KAAG,mBAEzD,CAAC;AAgCF,eAAO,MAAM,gBAAgB,GAAI,CAAC,SAAS,eAAe,EACxD,SAAS,CAAC,EACV,cAAa,OAAgF;;;CAuB9F,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,mBAAmB,EAAE,UAAU,CAAC,KAAG,MAK9E,CAAC;AAwBF,eAAO,MAAM,qBAAqB,GAAI,UAAU,mBAAmB,KAAG,MAuBrE,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,oBAAoB,GAAI,SAAS,eAAe,KAAG,MAI/D,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"http-adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/adapter/http-adapter.fetch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,kBAAkB,EAInB,MAAM,iBAAiB,CAAC;AAIzB,eAAO,MAAM,aAAa,QAAO,kBA2K5B,CAAC"}
1
+ {"version":3,"file":"http-adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/adapter/http-adapter.fetch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,kBAAkB,EAKnB,MAAM,iBAAiB,CAAC;AAIzB,eAAO,MAAM,aAAa,QAAO,kBAoL5B,CAAC"}
package/dist/index.mjs CHANGED
@@ -15,15 +15,42 @@ var GraphqlMethod = /* @__PURE__ */ function(GraphqlMethod) {
15
15
  }({});
16
16
  //#endregion
17
17
  //#region src/adapter/adapter.utils.ts
18
- var getRequestValues = (request) => {
18
+ var getDocumentOption = (request) => {
19
+ return request.requestOptions.document;
20
+ };
21
+ var hasDocumentOption = (request) => getDocumentOption(request) != null;
22
+ /** The document of the request - from the `document` option or, when it is omitted, from the `endpoint` */
23
+ var getGqlDocument = (request) => {
24
+ return getDocumentOption(request) ?? request.endpoint;
25
+ };
26
+ /** Query string keys owned by the GraphQL over HTTP GET format - they win over the user query params */
27
+ var reservedQueryParams = ["query", "variables"];
28
+ var isReservedQueryParam = (param) => {
29
+ const [rawKey] = param.split("=");
30
+ try {
31
+ return reservedQueryParams.includes(decodeURIComponent(rawKey).split("[")[0]);
32
+ } catch {
33
+ return false;
34
+ }
35
+ };
36
+ var omitReservedQueryParams = (queryString) => {
37
+ return queryString.replace(/^\?/, "").split("&").filter((param) => !isReservedQueryParam(param)).join("&");
38
+ };
39
+ var joinQueryStrings = (...queryStrings) => {
40
+ const joined = queryStrings.map((queryString) => queryString.replace(/^\?/, "")).filter(Boolean).join("&");
41
+ return joined ? `?${joined}` : "";
42
+ };
43
+ var getRequestValues = (request, queryParams = request.client.adapter.unstable_queryParamsMapper(request.queryParams)) => {
19
44
  const isPostRequest = request.method === HttpMethods.POST;
20
- const query = request.endpoint;
45
+ const query = gqlEndpointMapper(getGqlDocument(request));
21
46
  const variables = request.payload;
47
+ const url = hasDocumentOption(request) ? `${request.client.url}${request.endpoint}` : request.client.url;
48
+ const queryString = stringifyQueryParams(queryParams);
22
49
  return {
23
- fullUrl: isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({
50
+ fullUrl: isPostRequest ? url + joinQueryStrings(queryString) : url + joinQueryStrings(stringifyQueryParams({
24
51
  query,
25
52
  variables
26
- }),
53
+ }), omitReservedQueryParams(queryString)),
27
54
  payload: isPostRequest ? JSON.stringify({
28
55
  query,
29
56
  variables
@@ -34,19 +61,32 @@ var gqlEndpointMapper = (endpoint) => {
34
61
  if (typeof endpoint === "string") return endpoint;
35
62
  return print(endpoint);
36
63
  };
64
+ var getOperationName = (ast) => {
65
+ const operationDefinition = ast.definitions.find((def) => def.kind === "OperationDefinition");
66
+ if (operationDefinition) {
67
+ if (operationDefinition.name?.value) return operationDefinition.name.value;
68
+ const selection = operationDefinition.selectionSet.selections[0];
69
+ if (selection?.kind === "Field") return selection.name.value;
70
+ if (selection?.kind === "InlineFragment" && selection.typeCondition) return selection.typeCondition.name.value;
71
+ }
72
+ };
37
73
  var gqlEndpointNameMapper = (endpoint) => {
74
+ if (typeof endpoint !== "string") return getOperationName(endpoint) || "graphql-request";
38
75
  try {
39
- const operationDefinition = parse(endpoint).definitions.find((def) => def.kind === "OperationDefinition");
40
- if (operationDefinition) {
41
- if (operationDefinition.name?.value) return operationDefinition.name.value;
42
- const selection = operationDefinition.selectionSet.selections[0];
43
- if (selection?.kind === "Field") return selection.name.value;
44
- if (selection?.kind === "InlineFragment" && selection.typeCondition) return selection.typeCondition.name.value;
45
- }
76
+ const name = getOperationName(parse(endpoint));
77
+ if (name) return name;
46
78
  } catch {}
47
79
  const [name] = endpoint.replace(/(query|mutation|subscription)/, "").replaceAll(/[{}().,:]/g, " ").trim().split(" ");
48
80
  return name || "graphql-request";
49
81
  };
82
+ /**
83
+ * Name identifying the request in the cache, query and abort keys.
84
+ * With the `document` option the same operation can be sent to many paths, so the path is a part of the name.
85
+ */
86
+ var gqlRequestNameMapper = (request) => {
87
+ const name = gqlEndpointNameMapper(getGqlDocument(request));
88
+ return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;
89
+ };
50
90
  //#endregion
51
91
  //#region src/adapter/http-adapter.fetch.ts
52
92
  var getGqlAdapter = () => new Adapter({
@@ -57,16 +97,16 @@ var getGqlAdapter = () => new Adapter({
57
97
  systemErrorExtra: gqlExtra
58
98
  }).onInitialize(({ client }) => {
59
99
  client.setCacheKeyMapper((request) => {
60
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
100
+ return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
61
101
  });
62
102
  client.setQueryKeyMapper((request) => {
63
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
103
+ return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
64
104
  });
65
105
  client.setAbortKeyMapper((request) => {
66
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;
106
+ return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;
67
107
  });
68
- }).setInternalErrorMapping((error) => [error]).setDevtoolsEndpointGetter(gqlEndpointNameMapper).setEndpointMapper(gqlEndpointMapper).setFetcher(async ({ request, adapterOptions, headers, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
69
- const { fullUrl, payload } = getRequestValues(request);
108
+ }).setInternalErrorMapping((error) => [error]).setDevtoolsEndpointGetter((endpoint, requestOptions) => gqlEndpointNameMapper(requestOptions?.document ?? endpoint)).setEndpointMapper(gqlEndpointMapper).setQueryParamsMapper(stringifyQueryParams).setFetcher(async ({ request, queryParams, adapterOptions, headers, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
109
+ const { fullUrl, payload } = getRequestValues(request, queryParams);
70
110
  const controller = getAbortController();
71
111
  const { timeout: timeoutMs = defaultTimeout, ...restOptions } = adapterOptions || {};
72
112
  let timedOut = false;
@@ -178,6 +218,6 @@ var GraphqlAdapter = () => {
178
218
  return getGqlAdapter();
179
219
  };
180
220
  //#endregion
181
- export { GraphqlAdapter, GraphqlMethod, defaultTimeout, getGqlAdapter, getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlExtra };
221
+ export { GraphqlAdapter, GraphqlMethod, defaultTimeout, getGqlAdapter, getGqlDocument, getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlExtra, gqlRequestNameMapper };
182
222
 
183
223
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.constants.ts","../src/adapter/adapter.types.ts","../src/adapter/adapter.utils.ts","../src/adapter/http-adapter.fetch.ts","../src/adapter/adapter.ts"],"sourcesContent":["import { Time } from \"@hyper-fetch/core\";\n\nimport type { GraphQlExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const gqlExtra: GraphQlExtraType = {\n headers: {},\n extensions: {},\n};\n","import type { Adapter, EmptyTypes, QueryParamsType } from \"@hyper-fetch/core\";\nimport type { DocumentNode } from \"graphql/language/ast\";\n\nexport enum GraphqlMethod {\n POST = \"POST\",\n GET = \"GET\",\n}\n\nexport type GraphQlExtraType = { headers: HeadersInit; extensions: Record<string, any> };\n\nexport type GraphQlEndpointType = string | DocumentNode;\n\nexport type FetchGraphqlAdapterOptionsType = Omit<RequestInit, \"method\" | \"headers\" | \"body\" | \"signal\"> & {\n timeout?: number;\n};\n\nexport type GraphqlAdapterType = Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType,\n (endpoint: GraphQlEndpointType) => string\n>;\n\n// Extract\n\ntype GqlParamType = boolean | string | number | Record<string, any> | EmptyTypes;\n\nexport type ExtractGqlRouteParams<T extends string> = string extends T\n ? EmptyTypes\n : T extends `${string}query ${infer Parameters} {${infer QueryRest}`\n ? Parameters extends `${string}$${infer Param},${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : Parameters extends `${string}$${infer Param})${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : EmptyTypes\n : T extends `${string}$${infer Parameters},${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : T extends `${string}$${infer Parameters})${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : EmptyTypes;\n\nexport type GqlParameter<T extends string, Rest extends string> = T extends `${infer Param}:${string}!`\n ? { [k in Param]: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : T extends `${infer Param}:${string}`\n ? { [k in Param]?: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : EmptyTypes;\n","import type { RequestInstance } from \"@hyper-fetch/core\";\nimport { HttpMethods, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { OperationDefinitionNode } from \"graphql\";\nimport { print, parse } from \"graphql\";\n\nimport type { GraphQlEndpointType } from \"./adapter.types\";\n\nexport const getRequestValues = <R extends RequestInstance>(request: R) => {\n const isPostRequest = request.method === HttpMethods.POST;\n\n const query = request.endpoint;\n const variables = request.payload;\n\n const fullUrl = isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({ query, variables });\n\n const payload = isPostRequest\n ? JSON.stringify({\n query,\n variables,\n })\n : null;\n\n return { fullUrl, payload };\n};\n\nexport const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): string => {\n if (typeof endpoint === \"string\") {\n return endpoint;\n }\n return print(endpoint);\n};\n\nexport const gqlEndpointNameMapper = (endpoint: string): string => {\n try {\n const ast = parse(endpoint);\n const operationDefinition = ast.definitions.find(\n (def): def is OperationDefinitionNode => def.kind === \"OperationDefinition\",\n );\n\n if (operationDefinition) {\n if (operationDefinition.name?.value) {\n return operationDefinition.name.value;\n }\n\n const selection = operationDefinition.selectionSet.selections[0];\n if (selection?.kind === \"Field\") {\n return selection.name.value;\n }\n if (selection?.kind === \"InlineFragment\" && selection.typeCondition) {\n return selection.typeCondition.name.value;\n }\n }\n } catch {\n // We can ignore this error and just return some fallback\n }\n\n // Fallback for invalid gql queries or something else\n const clearedQuery = endpoint\n .replace(/(query|mutation|subscription)/, \"\")\n .replaceAll(/[{}().,:]/g, \" \")\n .trim();\n const [name] = clearedQuery.split(\" \");\n\n return name || \"graphql-request\";\n};\n","import type { QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, stringifyKey } from \"@hyper-fetch/core\";\n\nimport { gqlExtra, defaultTimeout } from \"./adapter.constants\";\nimport type {\n GraphqlAdapterType,\n GraphQlExtraType,\n GraphQlEndpointType,\n FetchGraphqlAdapterOptionsType,\n} from \"./adapter.types\";\nimport { GraphqlMethod } from \"./adapter.types\";\nimport { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper } from \"./adapter.utils\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n new Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n undefined,\n GraphQlEndpointType\n >({\n name: \"graphql\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setQueryKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter(gqlEndpointNameMapper)\n .setEndpointMapper(gqlEndpointMapper)\n .setFetcher(\n async ({\n request,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onSuccess,\n }) => {\n const { fullUrl, payload } = getRequestValues(request);\n\n const controller = getAbortController();\n const { timeout: timeoutMs = defaultTimeout, ...restOptions } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const unmountListener = createAbortListener({\n status: 0,\n extra: gqlExtra,\n });\n\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n onBeforeRequest();\n onRequestStart();\n\n try {\n const init: RequestInit = {\n method: request.method,\n headers: headers as Record<string, string>,\n signal: controller?.signal,\n ...restOptions,\n };\n\n if (payload) {\n init.body = payload;\n\n if (typeof payload === \"string\") {\n const total = new Blob([payload]).size;\n onRequestProgress({ total, loaded: total } as ProgressEvent);\n }\n }\n\n onRequestEnd();\n\n const response = await fetch(fullUrl, init);\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n let body: string;\n\n if (response.body && typeof response.body.getReader === \"function\") {\n const reader = response.body.getReader();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n receivedLength += value.length;\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n body = new TextDecoder().decode(allChunks);\n } else {\n body = await response.text();\n }\n\n onResponseEnd();\n unmountListener();\n\n const { status } = response;\n const parsed = parseResponse(body);\n const data = parsed?.data ?? null;\n const errors = parsed?.errors || null;\n const extensions = parsed?.extensions || {};\n const failure = errors || status > 399 || status === 0;\n\n if (failure) {\n const error = errors || [getErrorMessage()];\n onError({ error, status, extra: { headers: responseHeaders, extensions } });\n } else {\n onSuccess({\n data,\n error: errors,\n status,\n extra: { headers: responseHeaders, extensions },\n });\n }\n } catch (error: any) {\n if (timeoutId) clearTimeout(timeoutId);\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: gqlExtra });\n }\n return;\n }\n\n onError({ error: error, status: 0, extra: gqlExtra });\n }\n },\n );\n","import type { GraphqlAdapterType } from \"./adapter.types\";\nimport { getGqlAdapter } from \"./http-adapter.fetch\";\n\nexport const GraphqlAdapter = (): GraphqlAdapterType => {\n return getGqlAdapter();\n};\n"],"mappings":";;;AAIA,IAAa,iBAAiB,KAAK,MAAM;AAEzC,IAAa,WAA6B;CACxC,SAAS,EAAE;CACX,YAAY,EAAE;CACf;;;ACND,IAAY,gBAAL,yBAAA,eAAA;AACL,eAAA,UAAA;AACA,eAAA,SAAA;;KACD;;;ACCD,IAAa,oBAA+C,YAAe;CACzE,MAAM,gBAAgB,QAAQ,WAAW,YAAY;CAErD,MAAM,QAAQ,QAAQ;CACtB,MAAM,YAAY,QAAQ;AAW1B,QAAO;EAAE,SATO,gBAAgB,QAAQ,OAAO,MAAM,QAAQ,OAAO,MAAM,qBAAqB;GAAE;GAAO;GAAW,CAAC;EASlG,SAPF,gBACZ,KAAK,UAAU;GACb;GACA;GACD,CAAC,GACF;EAEuB;;AAG7B,IAAa,qBAAoD,aAAwB;AACvF,KAAI,OAAO,aAAa,SACtB,QAAO;AAET,QAAO,MAAM,SAAS;;AAGxB,IAAa,yBAAyB,aAA6B;AACjE,KAAI;EAEF,MAAM,sBADM,MAAM,SAAS,CACK,YAAY,MACzC,QAAwC,IAAI,SAAS,sBACvD;AAED,MAAI,qBAAqB;AACvB,OAAI,oBAAoB,MAAM,MAC5B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IAAI,aAAa,CAAC,OAAO,UAAU;QAE1C,QAAO,MAAM,SAAS,MAAM;AAG9B,iBAAe;AACf,mBAAiB;EAEjB,MAAM,EAAE,WAAW;EACnB,MAAM,SAAS,cAAc,KAAK;EAClC,MAAM,OAAO,QAAQ,QAAQ;EAC7B,MAAM,SAAS,QAAQ,UAAU;EACjC,MAAM,aAAa,QAAQ,cAAc,EAAE;AAG3C,MAFgB,UAAU,SAAS,OAAO,WAAW,EAInD,SAAQ;GAAE,OADI,UAAU,CAAC,iBAAiB,CAAC;GAC1B;GAAQ,OAAO;IAAE,SAAS;IAAiB;IAAY;GAAE,CAAC;MAE3E,WAAU;GACR;GACA,OAAO;GACP;GACA,OAAO;IAAE,SAAS;IAAiB;IAAY;GAChD,CAAC;UAEG,OAAY;AACnB,MAAI,UAAW,cAAa,UAAU;AACtC,mBAAiB;AAEjB,MAAI,YAAY,QAAQ,SAAS;AAC/B,OAAI,SACF,gBAAe;IAAE,QAAQ;IAAG,OAAO;IAAU,CAAC;AAEhD;;AAGF,UAAQ;GAAS;GAAO,QAAQ;GAAG,OAAO;GAAU,CAAC;;EAG1D;;;ACrLL,IAAa,uBAA2C;AACtD,QAAO,eAAe"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/adapter/adapter.constants.ts","../src/adapter/adapter.types.ts","../src/adapter/adapter.utils.ts","../src/adapter/http-adapter.fetch.ts","../src/adapter/adapter.ts"],"sourcesContent":["import { Time } from \"@hyper-fetch/core\";\n\nimport type { GraphQlExtraType } from \"./adapter.types\";\n\nexport const defaultTimeout = Time.SEC * 5;\n\nexport const gqlExtra: GraphQlExtraType = {\n headers: {},\n extensions: {},\n};\n","import type { Adapter, DefaultMapperType, EmptyTypes, QueryParamsType, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { DocumentNode } from \"graphql/language/ast\";\n\nexport enum GraphqlMethod {\n POST = \"POST\",\n GET = \"GET\",\n}\n\nexport type GraphQlExtraType = { headers: HeadersInit; extensions: Record<string, any> };\n\nexport type GraphQlEndpointType = string | DocumentNode;\n\nexport type FetchGraphqlAdapterOptionsType = Omit<RequestInit, \"method\" | \"headers\" | \"body\" | \"signal\"> & {\n timeout?: number;\n};\n\nexport type GraphqlRequestOptionsType = {\n /**\n * GraphQL document sent as `query`. When it is set, `endpoint` becomes a URL path appended to `client.url`,\n * the same way as in the HttpAdapter. When it is omitted, `endpoint` holds the document and the URL is `client.url`.\n */\n document?: GraphQlEndpointType;\n};\n\nexport type GraphqlAdapterType = Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n GraphQlEndpointType,\n (endpoint: GraphQlEndpointType) => string,\n typeof stringifyQueryParams,\n DefaultMapperType,\n DefaultMapperType,\n GraphqlRequestOptionsType\n>;\n\n// Extract\n\ntype GqlParamType = boolean | string | number | Record<string, any> | EmptyTypes;\n\nexport type ExtractGqlRouteParams<T extends string> = string extends T\n ? EmptyTypes\n : T extends `${string}query ${infer Parameters} {${infer QueryRest}`\n ? Parameters extends `${string}$${infer Param},${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : Parameters extends `${string}$${infer Param})${infer Rest}`\n ? GqlParameter<Param, Rest> &\n // eslint-disable-next-line @typescript-eslint/ban-types\n (ExtractGqlRouteParams<QueryRest> extends EmptyTypes ? {} : ExtractGqlRouteParams<QueryRest>)\n : EmptyTypes\n : T extends `${string}$${infer Parameters},${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : T extends `${string}$${infer Parameters})${infer Rest}`\n ? GqlParameter<Parameters, Rest>\n : EmptyTypes;\n\nexport type GqlParameter<T extends string, Rest extends string> = T extends `${infer Param}:${string}!`\n ? { [k in Param]: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : T extends `${infer Param}:${string}`\n ? { [k in Param]?: GqlParamType } & (ExtractGqlRouteParams<Rest> extends EmptyTypes\n ? // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n : ExtractGqlRouteParams<Rest>)\n : EmptyTypes;\n","import type { EmptyTypes, QueryParamsType, RequestInstance } from \"@hyper-fetch/core\";\nimport { HttpMethods, stringifyQueryParams } from \"@hyper-fetch/core\";\nimport type { DocumentNode, OperationDefinitionNode } from \"graphql\";\nimport { print, parse } from \"graphql\";\n\nimport type { GraphQlEndpointType, GraphqlRequestOptionsType } from \"./adapter.types\";\n\nconst getDocumentOption = (request: RequestInstance) => {\n return (request.requestOptions as unknown as GraphqlRequestOptionsType).document;\n};\n\nconst hasDocumentOption = (request: RequestInstance) => getDocumentOption(request) != null;\n\n/** The document of the request - from the `document` option or, when it is omitted, from the `endpoint` */\nexport const getGqlDocument = (request: RequestInstance): GraphQlEndpointType => {\n return getDocumentOption(request) ?? request.endpoint;\n};\n\n/** Query string keys owned by the GraphQL over HTTP GET format - they win over the user query params */\nconst reservedQueryParams = [\"query\", \"variables\"];\n\nconst isReservedQueryParam = (param: string) => {\n const [rawKey] = param.split(\"=\");\n try {\n // Array formats encode the key as `key[]` or `key[0]`\n return reservedQueryParams.includes(decodeURIComponent(rawKey).split(\"[\")[0]);\n } catch {\n return false;\n }\n};\n\nconst omitReservedQueryParams = (queryString: string) => {\n return queryString\n .replace(/^\\?/, \"\")\n .split(\"&\")\n .filter((param) => !isReservedQueryParam(param))\n .join(\"&\");\n};\n\nconst joinQueryStrings = (...queryStrings: string[]) => {\n const joined = queryStrings\n .map((queryString) => queryString.replace(/^\\?/, \"\"))\n .filter(Boolean)\n .join(\"&\");\n\n return joined ? `?${joined}` : \"\";\n};\n\nexport const getRequestValues = <R extends RequestInstance>(\n request: R,\n queryParams: unknown = request.client.adapter.unstable_queryParamsMapper(request.queryParams),\n) => {\n const isPostRequest = request.method === HttpMethods.POST;\n\n const query = gqlEndpointMapper(getGqlDocument(request));\n const variables = request.payload;\n\n const url = hasDocumentOption(request) ? `${request.client.url}${request.endpoint}` : request.client.url;\n // Mappers can return anything, so we normalize their result to the query string\n const queryString = stringifyQueryParams(queryParams as QueryParamsType | string | EmptyTypes);\n\n const fullUrl = isPostRequest\n ? url + joinQueryStrings(queryString)\n : url + joinQueryStrings(stringifyQueryParams({ query, variables }), omitReservedQueryParams(queryString));\n\n const payload = isPostRequest\n ? JSON.stringify({\n query,\n variables,\n })\n : null;\n\n return { fullUrl, payload };\n};\n\nexport const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): string => {\n if (typeof endpoint === \"string\") {\n return endpoint;\n }\n return print(endpoint);\n};\n\nconst getOperationName = (ast: DocumentNode): string | undefined => {\n const operationDefinition = ast.definitions.find(\n (def): def is OperationDefinitionNode => def.kind === \"OperationDefinition\",\n );\n\n if (operationDefinition) {\n if (operationDefinition.name?.value) {\n return operationDefinition.name.value;\n }\n\n const selection = operationDefinition.selectionSet.selections[0];\n if (selection?.kind === \"Field\") {\n return selection.name.value;\n }\n if (selection?.kind === \"InlineFragment\" && selection.typeCondition) {\n return selection.typeCondition.name.value;\n }\n }\n\n return undefined;\n};\n\nexport const gqlEndpointNameMapper = (endpoint: GraphQlEndpointType): string => {\n if (typeof endpoint !== \"string\") {\n return getOperationName(endpoint) || \"graphql-request\";\n }\n\n try {\n const name = getOperationName(parse(endpoint));\n\n if (name) {\n return name;\n }\n } catch {\n // We can ignore this error and just return some fallback\n }\n\n // Fallback for invalid gql queries or something else\n const clearedQuery = endpoint\n .replace(/(query|mutation|subscription)/, \"\")\n .replaceAll(/[{}().,:]/g, \" \")\n .trim();\n const [name] = clearedQuery.split(\" \");\n\n return name || \"graphql-request\";\n};\n\n/**\n * Name identifying the request in the cache, query and abort keys.\n * With the `document` option the same operation can be sent to many paths, so the path is a part of the name.\n */\nexport const gqlRequestNameMapper = (request: RequestInstance): string => {\n const name = gqlEndpointNameMapper(getGqlDocument(request));\n\n return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;\n};\n","import type { DefaultMapperType, QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, stringifyKey, stringifyQueryParams } from \"@hyper-fetch/core\";\n\nimport { gqlExtra, defaultTimeout } from \"./adapter.constants\";\nimport type {\n GraphqlAdapterType,\n GraphQlExtraType,\n GraphQlEndpointType,\n FetchGraphqlAdapterOptionsType,\n GraphqlRequestOptionsType,\n} from \"./adapter.types\";\nimport { GraphqlMethod } from \"./adapter.types\";\nimport { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlRequestNameMapper } from \"./adapter.utils\";\n\nexport const getGqlAdapter = (): GraphqlAdapterType =>\n new Adapter<\n FetchGraphqlAdapterOptionsType,\n GraphqlMethod,\n number,\n GraphQlExtraType,\n QueryParamsType | string,\n QueryParamsType | string | undefined,\n GraphQlEndpointType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n DefaultMapperType,\n GraphqlRequestOptionsType\n >({\n name: \"graphql\",\n defaultMethod: GraphqlMethod.POST,\n defaultExtra: gqlExtra,\n systemErrorStatus: 0,\n systemErrorExtra: gqlExtra,\n })\n .onInitialize(({ client }) => {\n client.setCacheKeyMapper((request) => {\n return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setQueryKeyMapper((request) => {\n return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n });\n client.setAbortKeyMapper((request) => {\n return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;\n });\n })\n .setInternalErrorMapping((error) => [error])\n .setDevtoolsEndpointGetter((endpoint, requestOptions) =>\n gqlEndpointNameMapper(requestOptions?.document ?? endpoint),\n )\n .setEndpointMapper(gqlEndpointMapper)\n .setQueryParamsMapper(stringifyQueryParams)\n .setFetcher(\n async ({\n request,\n queryParams,\n adapterOptions,\n headers,\n onError,\n onResponseEnd,\n onTimeoutError,\n onRequestEnd,\n createAbortListener,\n getAbortController,\n onResponseProgress,\n onResponseStart,\n onBeforeRequest,\n onRequestStart,\n onRequestProgress,\n onSuccess,\n }) => {\n const { fullUrl, payload } = getRequestValues(request, queryParams);\n\n const controller = getAbortController();\n const { timeout: timeoutMs = defaultTimeout, ...restOptions } = adapterOptions || {};\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const unmountListener = createAbortListener({\n status: 0,\n extra: gqlExtra,\n });\n\n if (timeoutMs > 0 && controller) {\n timeoutId = setTimeout(() => {\n timedOut = true;\n unmountListener();\n controller.abort();\n }, timeoutMs);\n }\n\n onBeforeRequest();\n onRequestStart();\n\n try {\n const init: RequestInit = {\n method: request.method,\n headers: headers as Record<string, string>,\n signal: controller?.signal,\n ...restOptions,\n };\n\n if (payload) {\n init.body = payload;\n\n if (typeof payload === \"string\") {\n const total = new Blob([payload]).size;\n onRequestProgress({ total, loaded: total } as ProgressEvent);\n }\n }\n\n onRequestEnd();\n\n const response = await fetch(fullUrl, init);\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n onResponseStart();\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n let body: string;\n\n if (response.body && typeof response.body.getReader === \"function\") {\n const reader = response.body.getReader();\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let receivedLength = 0;\n const chunks: Uint8Array[] = [];\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n chunks.push(value);\n receivedLength += value.length;\n onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);\n }\n\n const allChunks = new Uint8Array(receivedLength);\n let position = 0;\n // eslint-disable-next-line no-restricted-syntax\n for (const chunk of chunks) {\n allChunks.set(chunk, position);\n position += chunk.length;\n }\n body = new TextDecoder().decode(allChunks);\n } else {\n body = await response.text();\n }\n\n onResponseEnd();\n unmountListener();\n\n const { status } = response;\n const parsed = parseResponse(body);\n const data = parsed?.data ?? null;\n const errors = parsed?.errors || null;\n const extensions = parsed?.extensions || {};\n const failure = errors || status > 399 || status === 0;\n\n if (failure) {\n const error = errors || [getErrorMessage()];\n onError({ error, status, extra: { headers: responseHeaders, extensions } });\n } else {\n onSuccess({\n data,\n error: errors,\n status,\n extra: { headers: responseHeaders, extensions },\n });\n }\n } catch (error: any) {\n if (timeoutId) clearTimeout(timeoutId);\n unmountListener();\n\n if (controller?.signal?.aborted) {\n if (timedOut) {\n onTimeoutError({ status: 0, extra: gqlExtra });\n }\n return;\n }\n\n onError({ error: error, status: 0, extra: gqlExtra });\n }\n },\n );\n","import type { GraphqlAdapterType } from \"./adapter.types\";\nimport { getGqlAdapter } from \"./http-adapter.fetch\";\n\nexport const GraphqlAdapter = (): GraphqlAdapterType => {\n return getGqlAdapter();\n};\n"],"mappings":";;;AAIA,IAAa,iBAAiB,KAAK,MAAM;AAEzC,IAAa,WAA6B;CACxC,SAAS,EAAE;CACX,YAAY,EAAE;CACf;;;ACND,IAAY,gBAAL,yBAAA,eAAA;AACL,eAAA,UAAA;AACA,eAAA,SAAA;;KACD;;;ACCD,IAAM,qBAAqB,YAA6B;AACtD,QAAQ,QAAQ,eAAwD;;AAG1E,IAAM,qBAAqB,YAA6B,kBAAkB,QAAQ,IAAI;;AAGtF,IAAa,kBAAkB,YAAkD;AAC/E,QAAO,kBAAkB,QAAQ,IAAI,QAAQ;;;AAI/C,IAAM,sBAAsB,CAAC,SAAS,YAAY;AAElD,IAAM,wBAAwB,UAAkB;CAC9C,MAAM,CAAC,UAAU,MAAM,MAAM,IAAI;AACjC,KAAI;AAEF,SAAO,oBAAoB,SAAS,mBAAmB,OAAO,CAAC,MAAM,IAAI,CAAC,GAAG;SACvE;AACN,SAAO;;;AAI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AAmB;KAAE,OAAO,iBAAiB;KAAgB,QAAQ;KAAgB,CAAkB;;GAGzG,MAAM,YAAY,IAAI,WAAW,eAAe;GAChD,IAAI,WAAW;AAEf,QAAK,MAAM,SAAS,QAAQ;AAC1B,cAAU,IAAI,OAAO,SAAS;AAC9B,gBAAY,MAAM;;AAEpB,UAAO,IAAI,aAAa,CAAC,OAAO,UAAU;QAE1C,QAAO,MAAM,SAAS,MAAM;AAG9B,iBAAe;AACf,mBAAiB;EAEjB,MAAM,EAAE,WAAW;EACnB,MAAM,SAAS,cAAc,KAAK;EAClC,MAAM,OAAO,QAAQ,QAAQ;EAC7B,MAAM,SAAS,QAAQ,UAAU;EACjC,MAAM,aAAa,QAAQ,cAAc,EAAE;AAG3C,MAFgB,UAAU,SAAS,OAAO,WAAW,EAInD,SAAQ;GAAE,OADI,UAAU,CAAC,iBAAiB,CAAC;GAC1B;GAAQ,OAAO;IAAE,SAAS;IAAiB;IAAY;GAAE,CAAC;MAE3E,WAAU;GACR;GACA,OAAO;GACP;GACA,OAAO;IAAE,SAAS;IAAiB;IAAY;GAChD,CAAC;UAEG,OAAY;AACnB,MAAI,UAAW,cAAa,UAAU;AACtC,mBAAiB;AAEjB,MAAI,YAAY,QAAQ,SAAS;AAC/B,OAAI,SACF,gBAAe;IAAE,QAAQ;IAAG,OAAO;IAAU,CAAC;AAEhD;;AAGF,UAAQ;GAAS;GAAO,QAAQ;GAAG,OAAO;GAAU,CAAC;;EAG1D;;;AC/LL,IAAa,uBAA2C;AACtD,QAAO,eAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyper-fetch/graphql",
3
- "version": "9.3.0",
3
+ "version": "9.4.1",
4
4
  "description": "Simple graphql adapter",
5
5
  "author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
6
6
  "homepage": "https://hyperfetch.bettertyped.com/",
@@ -1,4 +1,4 @@
1
- import type { Adapter, EmptyTypes, QueryParamsType } from "@hyper-fetch/core";
1
+ import type { Adapter, DefaultMapperType, EmptyTypes, QueryParamsType, stringifyQueryParams } from "@hyper-fetch/core";
2
2
  import type { DocumentNode } from "graphql/language/ast";
3
3
 
4
4
  export enum GraphqlMethod {
@@ -14,15 +14,27 @@ export type FetchGraphqlAdapterOptionsType = Omit<RequestInit, "method" | "heade
14
14
  timeout?: number;
15
15
  };
16
16
 
17
+ export type GraphqlRequestOptionsType = {
18
+ /**
19
+ * GraphQL document sent as `query`. When it is set, `endpoint` becomes a URL path appended to `client.url`,
20
+ * the same way as in the HttpAdapter. When it is omitted, `endpoint` holds the document and the URL is `client.url`.
21
+ */
22
+ document?: GraphQlEndpointType;
23
+ };
24
+
17
25
  export type GraphqlAdapterType = Adapter<
18
26
  FetchGraphqlAdapterOptionsType,
19
27
  GraphqlMethod,
20
28
  number,
21
29
  GraphQlExtraType,
22
30
  QueryParamsType | string,
23
- undefined,
31
+ QueryParamsType | string | undefined,
24
32
  GraphQlEndpointType,
25
- (endpoint: GraphQlEndpointType) => string
33
+ (endpoint: GraphQlEndpointType) => string,
34
+ typeof stringifyQueryParams,
35
+ DefaultMapperType,
36
+ DefaultMapperType,
37
+ GraphqlRequestOptionsType
26
38
  >;
27
39
 
28
40
  // Extract
@@ -1,17 +1,67 @@
1
- import type { RequestInstance } from "@hyper-fetch/core";
1
+ import type { EmptyTypes, QueryParamsType, RequestInstance } from "@hyper-fetch/core";
2
2
  import { HttpMethods, stringifyQueryParams } from "@hyper-fetch/core";
3
- import type { OperationDefinitionNode } from "graphql";
3
+ import type { DocumentNode, OperationDefinitionNode } from "graphql";
4
4
  import { print, parse } from "graphql";
5
5
 
6
- import type { GraphQlEndpointType } from "./adapter.types";
6
+ import type { GraphQlEndpointType, GraphqlRequestOptionsType } from "./adapter.types";
7
7
 
8
- export const getRequestValues = <R extends RequestInstance>(request: R) => {
8
+ const getDocumentOption = (request: RequestInstance) => {
9
+ return (request.requestOptions as unknown as GraphqlRequestOptionsType).document;
10
+ };
11
+
12
+ const hasDocumentOption = (request: RequestInstance) => getDocumentOption(request) != null;
13
+
14
+ /** The document of the request - from the `document` option or, when it is omitted, from the `endpoint` */
15
+ export const getGqlDocument = (request: RequestInstance): GraphQlEndpointType => {
16
+ return getDocumentOption(request) ?? request.endpoint;
17
+ };
18
+
19
+ /** Query string keys owned by the GraphQL over HTTP GET format - they win over the user query params */
20
+ const reservedQueryParams = ["query", "variables"];
21
+
22
+ const isReservedQueryParam = (param: string) => {
23
+ const [rawKey] = param.split("=");
24
+ try {
25
+ // Array formats encode the key as `key[]` or `key[0]`
26
+ return reservedQueryParams.includes(decodeURIComponent(rawKey).split("[")[0]);
27
+ } catch {
28
+ return false;
29
+ }
30
+ };
31
+
32
+ const omitReservedQueryParams = (queryString: string) => {
33
+ return queryString
34
+ .replace(/^\?/, "")
35
+ .split("&")
36
+ .filter((param) => !isReservedQueryParam(param))
37
+ .join("&");
38
+ };
39
+
40
+ const joinQueryStrings = (...queryStrings: string[]) => {
41
+ const joined = queryStrings
42
+ .map((queryString) => queryString.replace(/^\?/, ""))
43
+ .filter(Boolean)
44
+ .join("&");
45
+
46
+ return joined ? `?${joined}` : "";
47
+ };
48
+
49
+ export const getRequestValues = <R extends RequestInstance>(
50
+ request: R,
51
+ queryParams: unknown = request.client.adapter.unstable_queryParamsMapper(request.queryParams),
52
+ ) => {
9
53
  const isPostRequest = request.method === HttpMethods.POST;
10
54
 
11
- const query = request.endpoint;
55
+ const query = gqlEndpointMapper(getGqlDocument(request));
12
56
  const variables = request.payload;
13
57
 
14
- const fullUrl = isPostRequest ? request.client.url : request.client.url + stringifyQueryParams({ query, variables });
58
+ const url = hasDocumentOption(request) ? `${request.client.url}${request.endpoint}` : request.client.url;
59
+ // Mappers can return anything, so we normalize their result to the query string
60
+ const queryString = stringifyQueryParams(queryParams as QueryParamsType | string | EmptyTypes);
61
+
62
+ const fullUrl = isPostRequest
63
+ ? url + joinQueryStrings(queryString)
64
+ : url + joinQueryStrings(stringifyQueryParams({ query, variables }), omitReservedQueryParams(queryString));
15
65
 
16
66
  const payload = isPostRequest
17
67
  ? JSON.stringify({
@@ -30,25 +80,38 @@ export const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): s
30
80
  return print(endpoint);
31
81
  };
32
82
 
33
- export const gqlEndpointNameMapper = (endpoint: string): string => {
83
+ const getOperationName = (ast: DocumentNode): string | undefined => {
84
+ const operationDefinition = ast.definitions.find(
85
+ (def): def is OperationDefinitionNode => def.kind === "OperationDefinition",
86
+ );
87
+
88
+ if (operationDefinition) {
89
+ if (operationDefinition.name?.value) {
90
+ return operationDefinition.name.value;
91
+ }
92
+
93
+ const selection = operationDefinition.selectionSet.selections[0];
94
+ if (selection?.kind === "Field") {
95
+ return selection.name.value;
96
+ }
97
+ if (selection?.kind === "InlineFragment" && selection.typeCondition) {
98
+ return selection.typeCondition.name.value;
99
+ }
100
+ }
101
+
102
+ return undefined;
103
+ };
104
+
105
+ export const gqlEndpointNameMapper = (endpoint: GraphQlEndpointType): string => {
106
+ if (typeof endpoint !== "string") {
107
+ return getOperationName(endpoint) || "graphql-request";
108
+ }
109
+
34
110
  try {
35
- const ast = parse(endpoint);
36
- const operationDefinition = ast.definitions.find(
37
- (def): def is OperationDefinitionNode => def.kind === "OperationDefinition",
38
- );
39
-
40
- if (operationDefinition) {
41
- if (operationDefinition.name?.value) {
42
- return operationDefinition.name.value;
43
- }
44
-
45
- const selection = operationDefinition.selectionSet.selections[0];
46
- if (selection?.kind === "Field") {
47
- return selection.name.value;
48
- }
49
- if (selection?.kind === "InlineFragment" && selection.typeCondition) {
50
- return selection.typeCondition.name.value;
51
- }
111
+ const name = getOperationName(parse(endpoint));
112
+
113
+ if (name) {
114
+ return name;
52
115
  }
53
116
  } catch {
54
117
  // We can ignore this error and just return some fallback
@@ -63,3 +126,13 @@ export const gqlEndpointNameMapper = (endpoint: string): string => {
63
126
 
64
127
  return name || "graphql-request";
65
128
  };
129
+
130
+ /**
131
+ * Name identifying the request in the cache, query and abort keys.
132
+ * With the `document` option the same operation can be sent to many paths, so the path is a part of the name.
133
+ */
134
+ export const gqlRequestNameMapper = (request: RequestInstance): string => {
135
+ const name = gqlEndpointNameMapper(getGqlDocument(request));
136
+
137
+ return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;
138
+ };
@@ -1,5 +1,5 @@
1
- import type { QueryParamsType } from "@hyper-fetch/core";
2
- import { parseResponse, getErrorMessage, Adapter, stringifyKey } from "@hyper-fetch/core";
1
+ import type { DefaultMapperType, QueryParamsType } from "@hyper-fetch/core";
2
+ import { parseResponse, getErrorMessage, Adapter, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
3
3
 
4
4
  import { gqlExtra, defaultTimeout } from "./adapter.constants";
5
5
  import type {
@@ -7,9 +7,10 @@ import type {
7
7
  GraphQlExtraType,
8
8
  GraphQlEndpointType,
9
9
  FetchGraphqlAdapterOptionsType,
10
+ GraphqlRequestOptionsType,
10
11
  } from "./adapter.types";
11
12
  import { GraphqlMethod } from "./adapter.types";
12
- import { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper } from "./adapter.utils";
13
+ import { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlRequestNameMapper } from "./adapter.utils";
13
14
 
14
15
  export const getGqlAdapter = (): GraphqlAdapterType =>
15
16
  new Adapter<
@@ -18,8 +19,13 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
18
19
  number,
19
20
  GraphQlExtraType,
20
21
  QueryParamsType | string,
21
- undefined,
22
- GraphQlEndpointType
22
+ QueryParamsType | string | undefined,
23
+ GraphQlEndpointType,
24
+ DefaultMapperType,
25
+ DefaultMapperType,
26
+ DefaultMapperType,
27
+ DefaultMapperType,
28
+ GraphqlRequestOptionsType
23
29
  >({
24
30
  name: "graphql",
25
31
  defaultMethod: GraphqlMethod.POST,
@@ -29,21 +35,25 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
29
35
  })
30
36
  .onInitialize(({ client }) => {
31
37
  client.setCacheKeyMapper((request) => {
32
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
38
+ return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
33
39
  });
34
40
  client.setQueryKeyMapper((request) => {
35
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
41
+ return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
36
42
  });
37
43
  client.setAbortKeyMapper((request) => {
38
- return `${request.method}_${gqlEndpointNameMapper(request.endpoint)}-${request.cancelable}`;
44
+ return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;
39
45
  });
40
46
  })
41
47
  .setInternalErrorMapping((error) => [error])
42
- .setDevtoolsEndpointGetter(gqlEndpointNameMapper)
48
+ .setDevtoolsEndpointGetter((endpoint, requestOptions) =>
49
+ gqlEndpointNameMapper(requestOptions?.document ?? endpoint),
50
+ )
43
51
  .setEndpointMapper(gqlEndpointMapper)
52
+ .setQueryParamsMapper(stringifyQueryParams)
44
53
  .setFetcher(
45
54
  async ({
46
55
  request,
56
+ queryParams,
47
57
  adapterOptions,
48
58
  headers,
49
59
  onError,
@@ -59,7 +69,7 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
59
69
  onRequestProgress,
60
70
  onSuccess,
61
71
  }) => {
62
- const { fullUrl, payload } = getRequestValues(request);
72
+ const { fullUrl, payload } = getRequestValues(request, queryParams);
63
73
 
64
74
  const controller = getAbortController();
65
75
  const { timeout: timeoutMs = defaultTimeout, ...restOptions } = adapterOptions || {};