@hyper-fetch/graphql 9.6.0 → 9.6.2

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.
@@ -188,7 +188,7 @@ describe("Graphql Adapter [ Browser ]", () => {
188
188
 
189
189
  expect(data).toBeNull();
190
190
  expect(status).toBe(0);
191
- expect(error).toBe(networkError);
191
+ expect(error).toEqual([networkError]);
192
192
 
193
193
  global.fetch = originalFetch;
194
194
  });
@@ -0,0 +1,206 @@
1
+ import { Client, getErrorMessage } from "@hyper-fetch/core";
2
+ import { GraphqlAdapter, GraphqlMethod } from "adapter";
3
+
4
+ const url = "https://shared-base-url/graphql";
5
+ // Typed as plain strings: literals would also make the adapter infer the variables from the query text
6
+ const queryWithId = "query Q($id: ID!) { a(id: $id) }" as string;
7
+ const queryWithFilter = "query Q($filter: Filter) { a(filter: $filter) }" as string;
8
+
9
+ /** How the adapter turns every kind of GraphQL over HTTP response into a HyperFetch response. */
10
+ describe("Graphql Adapter [ Responses ]", () => {
11
+ let client = new Client({ url }).setAdapter(GraphqlAdapter());
12
+ let fetchSpy = vi.spyOn(globalThis, "fetch");
13
+
14
+ const respond = (body: string, init: { status?: number; headers?: Record<string, string> } = {}) => {
15
+ fetchSpy.mockResolvedValue(
16
+ new Response(body, {
17
+ status: init.status ?? 200,
18
+ headers: { "content-type": "application/json", ...init.headers },
19
+ }),
20
+ );
21
+ };
22
+
23
+ const send = () => client.createRequest<{ response: { a: number } }>()({ endpoint: "query Q { a }" }).send();
24
+
25
+ beforeEach(() => {
26
+ client = new Client({ url }).setAdapter(GraphqlAdapter());
27
+ fetchSpy = vi.spyOn(globalThis, "fetch");
28
+ });
29
+
30
+ afterEach(() => {
31
+ fetchSpy.mockRestore();
32
+ });
33
+
34
+ describe("when the request succeeds", () => {
35
+ it("should return the data", async () => {
36
+ respond('{"data":{"a":1}}');
37
+
38
+ expect(await send()).toMatchObject({ data: { a: 1 }, error: null, success: true, status: 200 });
39
+ });
40
+
41
+ it("should treat an empty errors list as success", async () => {
42
+ respond('{"data":{"a":1},"errors":[]}');
43
+
44
+ expect(await send()).toMatchObject({ data: { a: 1 }, error: null, success: true, status: 200 });
45
+ });
46
+
47
+ it("should return null data when the server sends null", async () => {
48
+ respond('{"data":null}');
49
+
50
+ expect(await send()).toMatchObject({ data: null, error: null, success: true });
51
+ });
52
+
53
+ it("should expose the response headers and extensions", async () => {
54
+ respond('{"data":{"a":1},"extensions":{"cost":5}}', { headers: { "x-trace": "abc" } });
55
+
56
+ const response = await send();
57
+
58
+ expect(response.extra?.extensions).toEqual({ cost: 5 });
59
+ expect(response.extra?.headers).toMatchObject({ "x-trace": "abc" });
60
+ });
61
+
62
+ it("should default the extensions to an empty object", async () => {
63
+ respond('{"data":{"a":1}}');
64
+
65
+ const response = await send();
66
+
67
+ expect(response.extra?.extensions).toEqual({});
68
+ });
69
+ });
70
+
71
+ describe("when the request fails", () => {
72
+ it("should return the GraphQL errors of a 200 response", async () => {
73
+ respond('{"data":null,"errors":[{"message":"Not allowed","path":["a"]}]}');
74
+
75
+ expect(await send()).toMatchObject({
76
+ data: null,
77
+ error: [{ message: "Not allowed", path: ["a"] }],
78
+ success: false,
79
+ status: 200,
80
+ });
81
+ });
82
+
83
+ it("should fail when errors come together with partial data", async () => {
84
+ respond('{"data":{"a":1},"errors":[{"message":"Partial"}]}');
85
+
86
+ expect(await send()).toMatchObject({ data: null, error: [{ message: "Partial" }], success: false });
87
+ });
88
+
89
+ it.each([400, 401, 403, 404, 500, 503])("should return the errors of a %i response", async (status) => {
90
+ respond('{"errors":[{"message":"Bad"}]}', { status });
91
+
92
+ expect(await send()).toMatchObject({ data: null, error: [{ message: "Bad" }], success: false, status });
93
+ });
94
+
95
+ it.each([
96
+ ["an HTML error page", "<html>Bad gateway</html>"],
97
+ ["an empty body", ""],
98
+ ["a JSON body without errors", '{"message":"down"}'],
99
+ ])("should return the default error for a failed response with %s", async (_name, body) => {
100
+ respond(body, { status: 502 });
101
+
102
+ expect(await send()).toMatchObject({ data: null, error: [getErrorMessage()], success: false, status: 502 });
103
+ });
104
+
105
+ it("should return a network failure as a list of errors", async () => {
106
+ const failure = new TypeError("Failed to fetch");
107
+ fetchSpy.mockRejectedValue(failure);
108
+
109
+ const response = await send();
110
+
111
+ expect(response).toMatchObject({ data: null, success: false, status: 0 });
112
+ expect(response.error).toEqual([failure]);
113
+ expect(Array.isArray(response.error)).toBe(true);
114
+ });
115
+
116
+ it("should return an abort as a list of errors", async () => {
117
+ fetchSpy.mockImplementation(
118
+ (_input, init) =>
119
+ new Promise((_resolve, reject) => {
120
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
121
+ }),
122
+ );
123
+ const request = client.createRequest<{ response: { a: number } }>()({ endpoint: "query Q { a }" });
124
+
125
+ const sent = request.send();
126
+ await vi.waitFor(() => expect(fetchSpy).toHaveBeenCalledTimes(1));
127
+ request.abort();
128
+ const response = await sent;
129
+
130
+ expect(response.error).toEqual([getErrorMessage("abort")]);
131
+ expect(response.status).toBe(0);
132
+ });
133
+
134
+ it("should return a timeout as an error", async () => {
135
+ fetchSpy.mockImplementation(
136
+ (_input, init) =>
137
+ new Promise((_resolve, reject) => {
138
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
139
+ }),
140
+ );
141
+ const request = client.createRequest<{ response: { a: number } }>()({
142
+ endpoint: "query Q { a }",
143
+ options: { timeout: 10 },
144
+ });
145
+
146
+ const response = await request.send();
147
+
148
+ expect(response.success).toBe(false);
149
+ expect(response.status).toBe(0);
150
+ expect(response.error).toEqual(getErrorMessage("timeout"));
151
+ });
152
+ });
153
+
154
+ describe("when sending the operation", () => {
155
+ it("should POST the query and the variables as JSON", async () => {
156
+ respond('{"data":{"a":1}}');
157
+ const request = client.createRequest<{ response: { a: number }; payload: { id: number } }>()({
158
+ endpoint: queryWithId,
159
+ headers: { Authorization: "Bearer token" },
160
+ });
161
+
162
+ await request.send({ payload: { id: 7 } });
163
+
164
+ const [input, init] = fetchSpy.mock.calls[0];
165
+ expect(String(input)).toBe(url);
166
+ expect(init?.method).toBe("POST");
167
+ expect(JSON.parse(String(init?.body))).toEqual({
168
+ query: queryWithId,
169
+ variables: { id: 7 },
170
+ });
171
+ expect(init?.headers).toMatchObject({ Authorization: "Bearer token" });
172
+ });
173
+
174
+ it("should GET the query and the JSON encoded variables in the url, without a body", async () => {
175
+ respond('{"data":{"a":1}}');
176
+ const request = client.createRequest<{
177
+ response: { a: number };
178
+ payload: { filter: { q: string; tags: string[] } };
179
+ }>()({
180
+ endpoint: queryWithFilter,
181
+ method: GraphqlMethod.GET,
182
+ });
183
+
184
+ await request.send({ payload: { filter: { q: "x y&z=1", tags: ["ą", "b"] } } });
185
+
186
+ const [input, init] = fetchSpy.mock.calls[0];
187
+ const params = new URL(String(input)).searchParams;
188
+ expect(params.get("query")).toBe(queryWithFilter);
189
+ expect(JSON.parse(params.get("variables") ?? "")).toEqual({ filter: { q: "x y&z=1", tags: ["ą", "b"] } });
190
+ expect(init?.method).toBe("GET");
191
+ expect(init?.body).toBeUndefined();
192
+ });
193
+
194
+ it("should pass fetch options through", async () => {
195
+ respond('{"data":{"a":1}}');
196
+ const request = client.createRequest<{ response: { a: number } }>()({
197
+ endpoint: "query Q { a }",
198
+ options: { credentials: "include", mode: "cors", cache: "no-store" },
199
+ });
200
+
201
+ await request.send();
202
+
203
+ expect(fetchSpy.mock.calls[0][1]).toMatchObject({ credentials: "include", mode: "cors", cache: "no-store" });
204
+ });
205
+ });
206
+ });
@@ -0,0 +1,170 @@
1
+ import { Client } from "@hyper-fetch/core";
2
+ import { GraphqlAdapter, GraphqlMethod } from "adapter";
3
+
4
+ const url = "https://shared-base-url/graphql";
5
+ // Typed as a plain string: a literal would also make the adapter infer the variables from the query text
6
+ const getUser = "query GetUser($id: ID!) { user(id: $id) { name } }" as string;
7
+ const search = "query Search($filter: Filter) { search(filter: $filter) { name } }" as string;
8
+
9
+ type UserResponse = { user: { name: string } };
10
+
11
+ /**
12
+ * The same operation with other variables is another query. It needs its own cache entry and its own queue -
13
+ * otherwise `GetUser(id: 2)` would show the cached user 1 or be deduplicated into its request.
14
+ */
15
+ describe("Graphql Adapter [ Variables ]", () => {
16
+ // The cache is only kept in the "client" mode
17
+ const createClient = () => new Client({ url, mode: "client" }).setAdapter(GraphqlAdapter());
18
+
19
+ let client = createClient();
20
+ let fetchSpy = vi.spyOn(globalThis, "fetch");
21
+
22
+ /** Answer every request with the user whose id was sent in the variables */
23
+ const answerWithRequestedUser = () => {
24
+ fetchSpy.mockImplementation(async (input, init) => {
25
+ const fromBody = init?.body ? JSON.parse(String(init.body)).variables : undefined;
26
+ const fromUrl = new URL(String(input)).searchParams.get("variables");
27
+ const variables = fromBody ?? (fromUrl ? JSON.parse(fromUrl) : {});
28
+ return Response.json({ data: { user: { name: `User ${variables.id}` } } });
29
+ });
30
+ };
31
+
32
+ beforeEach(() => {
33
+ client = createClient();
34
+ fetchSpy = vi.spyOn(globalThis, "fetch");
35
+ });
36
+
37
+ afterEach(() => {
38
+ fetchSpy.mockRestore();
39
+ });
40
+
41
+ describe("when building keys", () => {
42
+ it("should give requests with different variables different cache and query keys", () => {
43
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
44
+ endpoint: getUser,
45
+ });
46
+ const first = request.setPayload({ id: 1 });
47
+ const second = request.setPayload({ id: 2 });
48
+
49
+ expect(first.cacheKey).not.toBe(second.cacheKey);
50
+ expect(first.queryKey).not.toBe(second.queryKey);
51
+ });
52
+
53
+ it("should give requests with equal variables the same keys", () => {
54
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
55
+ endpoint: getUser,
56
+ });
57
+
58
+ expect(request.setPayload({ id: 1 }).cacheKey).toBe(request.setPayload({ id: 1 }).cacheKey);
59
+ expect(request.setPayload({ id: 1 }).queryKey).toBe(request.setPayload({ id: 1 }).queryKey);
60
+ });
61
+
62
+ it("should keep the keys of a request without variables unchanged", () => {
63
+ const request = client.createRequest<{ response: UserResponse }>()({
64
+ endpoint: "query GetUsers { users { name } }",
65
+ });
66
+
67
+ expect(request.cacheKey).toBe("POST_GetUsers--");
68
+ expect(request.queryKey).toBe("POST_GetUsers--");
69
+ });
70
+
71
+ it("should keep one abort key for an operation, whatever its variables", () => {
72
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
73
+ endpoint: getUser,
74
+ });
75
+
76
+ expect(request.setPayload({ id: 1 }).abortKey).toBe(request.setPayload({ id: 2 }).abortKey);
77
+ });
78
+
79
+ it.each([
80
+ [
81
+ "nested objects",
82
+ { filter: { tags: ["a", "b"], range: { from: 1 } } },
83
+ { filter: { tags: ["a", "c"], range: { from: 1 } } },
84
+ ],
85
+ ["null and a value", { id: null }, { id: 1 }],
86
+ ["numbers and strings", { id: 1 }, { id: "1" }],
87
+ ["booleans", { active: true }, { active: false }],
88
+ ["empty and filled lists", { ids: [] }, { ids: [1] }],
89
+ ])("should tell apart variables that differ in %s", (_name, left, right) => {
90
+ const request = client.createRequest<{ response: UserResponse; payload: Record<string, unknown> }>()({
91
+ endpoint: search,
92
+ });
93
+
94
+ expect(request.setPayload(left).cacheKey).not.toBe(request.setPayload(right).cacheKey);
95
+ });
96
+
97
+ it("should respect a cache key set by hand", () => {
98
+ const request = client
99
+ .createRequest<{ response: UserResponse; payload: { id: number } }>()({ endpoint: getUser })
100
+ .setCacheKey("my-key");
101
+
102
+ expect(request.setPayload({ id: 1 }).cacheKey).toBe("my-key");
103
+ expect(request.setPayload({ id: 2 }).cacheKey).toBe("my-key");
104
+ });
105
+
106
+ it("should use the variables passed to send()", async () => {
107
+ answerWithRequestedUser();
108
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
109
+ endpoint: getUser,
110
+ });
111
+
112
+ await request.send({ payload: { id: 1 } });
113
+ await request.send({ payload: { id: 2 } });
114
+
115
+ expect(request.setPayload({ id: 1 }).read()?.data).toEqual({ user: { name: "User 1" } });
116
+ expect(request.setPayload({ id: 2 }).read()?.data).toEqual({ user: { name: "User 2" } });
117
+ });
118
+ });
119
+
120
+ describe.each([GraphqlMethod.POST, GraphqlMethod.GET])("when sending %s queries", (method) => {
121
+ it("should cache every set of variables on its own", async () => {
122
+ answerWithRequestedUser();
123
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
124
+ endpoint: getUser,
125
+ method,
126
+ });
127
+ const first = request.setPayload({ id: 1 });
128
+ const second = request.setPayload({ id: 2 });
129
+
130
+ const [firstResponse, secondResponse] = await Promise.all([first.send(), second.send()]);
131
+
132
+ expect(firstResponse.data).toEqual({ user: { name: "User 1" } });
133
+ expect(secondResponse.data).toEqual({ user: { name: "User 2" } });
134
+ expect(first.read()?.data).toEqual({ user: { name: "User 1" } });
135
+ expect(second.read()?.data).toEqual({ user: { name: "User 2" } });
136
+ });
137
+
138
+ it("should not deduplicate requests with different variables", async () => {
139
+ answerWithRequestedUser();
140
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
141
+ endpoint: getUser,
142
+ method,
143
+ deduplicate: true,
144
+ });
145
+
146
+ const responses = await Promise.all([
147
+ request.setPayload({ id: 1 }).send(),
148
+ request.setPayload({ id: 2 }).send(),
149
+ request.setPayload({ id: 1 }).send(),
150
+ ]);
151
+
152
+ expect(responses.map((response) => response.data?.user.name)).toEqual(["User 1", "User 2", "User 1"]);
153
+ // The two requests for user 1 share one network call
154
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
155
+ });
156
+
157
+ it("should run queued requests with different variables side by side", async () => {
158
+ answerWithRequestedUser();
159
+ const request = client.createRequest<{ response: UserResponse; payload: { id: number } }>()({
160
+ endpoint: getUser,
161
+ method,
162
+ queued: true,
163
+ });
164
+
165
+ const responses = await Promise.all([1, 2, 3].map((id) => request.setPayload({ id }).send()));
166
+
167
+ expect(responses.map((response) => response.data?.user.name)).toEqual(["User 1", "User 2", "User 3"]);
168
+ });
169
+ });
170
+ });
@@ -13,4 +13,9 @@ export declare const gqlEndpointNameMapper: (endpoint: GraphQlEndpointType) => s
13
13
  * With the `document` option the same operation can be sent to many paths, so the path is a part of the name.
14
14
  */
15
15
  export declare const gqlRequestNameMapper: (request: RequestInstance) => string;
16
+ /**
17
+ * Cache and query key of a request. The variables are a part of it: the same operation with other variables is
18
+ * another query, with its own cached data and its own place in the queue.
19
+ */
20
+ export declare const gqlRequestKeyMapper: (request: RequestInstance) => string;
16
21
  //# 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,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
+ {"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;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,GAAI,SAAS,eAAe,KAAG,MAK9D,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,EAKnB,MAAM,iBAAiB,CAAC;AAIzB,eAAO,MAAM,aAAa,QAAO,kBAoL5B,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;AAUzB,eAAO,MAAM,aAAa,QAAO,kBAkL5B,CAAC"}
package/dist/index.mjs CHANGED
@@ -87,6 +87,15 @@ var gqlRequestNameMapper = (request) => {
87
87
  const name = gqlEndpointNameMapper(getGqlDocument(request));
88
88
  return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;
89
89
  };
90
+ /**
91
+ * Cache and query key of a request. The variables are a part of it: the same operation with other variables is
92
+ * another query, with its own cached data and its own place in the queue.
93
+ */
94
+ var gqlRequestKeyMapper = (request) => {
95
+ const key = `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
96
+ const variables = stringifyKey(request.payload);
97
+ return variables ? `${key}-${variables}` : key;
98
+ };
90
99
  //#endregion
91
100
  //#region src/adapter/http-adapter.fetch.ts
92
101
  var getGqlAdapter = () => new Adapter({
@@ -96,12 +105,8 @@ var getGqlAdapter = () => new Adapter({
96
105
  systemErrorStatus: 0,
97
106
  systemErrorExtra: gqlExtra
98
107
  }).onInitialize(({ client }) => {
99
- client.setCacheKeyMapper((request) => {
100
- return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
101
- });
102
- client.setQueryKeyMapper((request) => {
103
- return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
104
- });
108
+ client.setCacheKeyMapper(gqlRequestKeyMapper);
109
+ client.setQueryKeyMapper(gqlRequestKeyMapper);
105
110
  client.setAbortKeyMapper((request) => {
106
111
  return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;
107
112
  });
@@ -176,7 +181,7 @@ var getGqlAdapter = () => new Adapter({
176
181
  const { status } = response;
177
182
  const parsed = parseResponse(body);
178
183
  const data = parsed?.data ?? null;
179
- const errors = parsed?.errors || null;
184
+ const errors = Array.isArray(parsed?.errors) && parsed.errors.length === 0 ? null : parsed?.errors || null;
180
185
  const extensions = parsed?.extensions || {};
181
186
  if (errors || status > 399 || status === 0) onError({
182
187
  error: errors || [getErrorMessage()],
@@ -206,7 +211,7 @@ var getGqlAdapter = () => new Adapter({
206
211
  return;
207
212
  }
208
213
  onError({
209
- error,
214
+ error: [error],
210
215
  status: 0,
211
216
  extra: gqlExtra
212
217
  });
@@ -218,6 +223,6 @@ var GraphqlAdapter = () => {
218
223
  return getGqlAdapter();
219
224
  };
220
225
  //#endregion
221
- export { GraphqlAdapter, GraphqlMethod, defaultTimeout, getGqlAdapter, getGqlDocument, getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlExtra, gqlRequestNameMapper };
226
+ export { GraphqlAdapter, GraphqlMethod, defaultTimeout, getGqlAdapter, getGqlDocument, getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlExtra, gqlRequestKeyMapper, gqlRequestNameMapper };
222
227
 
223
228
  //# 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, 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":";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iB;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"}
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, stringifyKey, 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\n/**\n * Cache and query key of a request. The variables are a part of it: the same operation with other variables is\n * another query, with its own cached data and its own place in the queue.\n */\nexport const gqlRequestKeyMapper = (request: RequestInstance): string => {\n const key = `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;\n const variables = stringifyKey(request.payload);\n\n return variables ? `${key}-${variables}` : key;\n};\n","import type { DefaultMapperType, QueryParamsType } from \"@hyper-fetch/core\";\nimport { parseResponse, getErrorMessage, Adapter, 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 {\n getRequestValues,\n gqlEndpointMapper,\n gqlEndpointNameMapper,\n gqlRequestKeyMapper,\n gqlRequestNameMapper,\n} 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(gqlRequestKeyMapper);\n client.setQueryKeyMapper(gqlRequestKeyMapper);\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 // An empty `errors` list is not a failure\n const errors = Array.isArray(parsed?.errors) && parsed.errors.length === 0 ? null : 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 // Errors are always a list, like the GraphQL `errors` and the abort and timeout errors\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;;;AAIX,IAAM,2BAA2B,gBAAwB;AACvD,QAAO,YACJ,QAAQ,OAAO,GAAG,CAClB,MAAM,IAAI,CACV,QAAQ,UAAU,CAAC,qBAAqB,MAAM,CAAC,CAC/C,KAAK,IAAI;;AAGd,IAAM,oBAAoB,GAAG,iBAA2B;CACtD,MAAM,SAAS,aACZ,KAAK,gBAAg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,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;EAE7B,MAAM,SAAS,MAAM,QAAQ,QAAQ,OAAO,IAAI,OAAO,OAAO,WAAW,IAAI,OAAO,QAAQ,UAAU;EACtG,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;;AAIF,UAAQ;GAAE,OAAO,CAAC,MAAM;GAAE,QAAQ;GAAG,OAAO;GAAU,CAAC;;EAG5D;;;ACnML,IAAa,uBAA2C;AACtD,QAAO,eAAe"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyper-fetch/graphql",
3
- "version": "9.6.0",
3
+ "version": "9.6.2",
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,5 +1,5 @@
1
1
  import type { EmptyTypes, QueryParamsType, RequestInstance } from "@hyper-fetch/core";
2
- import { HttpMethods, stringifyQueryParams } from "@hyper-fetch/core";
2
+ import { HttpMethods, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
3
3
  import type { DocumentNode, OperationDefinitionNode } from "graphql";
4
4
  import { print, parse } from "graphql";
5
5
 
@@ -136,3 +136,14 @@ export const gqlRequestNameMapper = (request: RequestInstance): string => {
136
136
 
137
137
  return hasDocumentOption(request) ? `${name}${request.requestOptions.endpoint}` : name;
138
138
  };
139
+
140
+ /**
141
+ * Cache and query key of a request. The variables are a part of it: the same operation with other variables is
142
+ * another query, with its own cached data and its own place in the queue.
143
+ */
144
+ export const gqlRequestKeyMapper = (request: RequestInstance): string => {
145
+ const key = `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
146
+ const variables = stringifyKey(request.payload);
147
+
148
+ return variables ? `${key}-${variables}` : key;
149
+ };
@@ -1,5 +1,5 @@
1
1
  import type { DefaultMapperType, QueryParamsType } from "@hyper-fetch/core";
2
- import { parseResponse, getErrorMessage, Adapter, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
2
+ import { parseResponse, getErrorMessage, Adapter, stringifyQueryParams } from "@hyper-fetch/core";
3
3
 
4
4
  import { gqlExtra, defaultTimeout } from "./adapter.constants";
5
5
  import type {
@@ -10,7 +10,13 @@ import type {
10
10
  GraphqlRequestOptionsType,
11
11
  } from "./adapter.types";
12
12
  import { GraphqlMethod } from "./adapter.types";
13
- import { getRequestValues, gqlEndpointMapper, gqlEndpointNameMapper, gqlRequestNameMapper } from "./adapter.utils";
13
+ import {
14
+ getRequestValues,
15
+ gqlEndpointMapper,
16
+ gqlEndpointNameMapper,
17
+ gqlRequestKeyMapper,
18
+ gqlRequestNameMapper,
19
+ } from "./adapter.utils";
14
20
 
15
21
  export const getGqlAdapter = (): GraphqlAdapterType =>
16
22
  new Adapter<
@@ -34,12 +40,8 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
34
40
  systemErrorExtra: gqlExtra,
35
41
  })
36
42
  .onInitialize(({ client }) => {
37
- client.setCacheKeyMapper((request) => {
38
- return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
39
- });
40
- client.setQueryKeyMapper((request) => {
41
- return `${request.method}_${gqlRequestNameMapper(request)}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
42
- });
43
+ client.setCacheKeyMapper(gqlRequestKeyMapper);
44
+ client.setQueryKeyMapper(gqlRequestKeyMapper);
43
45
  client.setAbortKeyMapper((request) => {
44
46
  return `${request.method}_${gqlRequestNameMapper(request)}-${request.cancelable}`;
45
47
  });
@@ -163,7 +165,8 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
163
165
  const { status } = response;
164
166
  const parsed = parseResponse(body);
165
167
  const data = parsed?.data ?? null;
166
- const errors = parsed?.errors || null;
168
+ // An empty `errors` list is not a failure
169
+ const errors = Array.isArray(parsed?.errors) && parsed.errors.length === 0 ? null : parsed?.errors || null;
167
170
  const extensions = parsed?.extensions || {};
168
171
  const failure = errors || status > 399 || status === 0;
169
172
 
@@ -189,7 +192,8 @@ export const getGqlAdapter = (): GraphqlAdapterType =>
189
192
  return;
190
193
  }
191
194
 
192
- onError({ error: error, status: 0, extra: gqlExtra });
195
+ // Errors are always a list, like the GraphQL `errors` and the abort and timeout errors
196
+ onError({ error: [error], status: 0, extra: gqlExtra });
193
197
  }
194
198
  },
195
199
  );