@hyper-fetch/graphql 9.9.0 → 10.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +152 -84
- package/__tests__/e2e/e2e.conformance.spec.ts +206 -0
- package/__tests__/e2e/e2e.graphql-ws-server.ts +187 -0
- package/__tests__/e2e/e2e.graphql-ws.spec.ts +306 -0
- package/__tests__/e2e/e2e.react-subscriptions.spec.tsx +208 -0
- package/__tests__/features/adapter/adapter.browser.spec.ts +23 -5
- package/__tests__/features/adapter/adapter.document.spec.ts +17 -13
- package/__tests__/features/adapter/adapter.headers.spec.ts +65 -0
- package/__tests__/features/adapter/adapter.keys.spec.ts +235 -0
- package/__tests__/features/adapter/adapter.persisted-queries.spec.ts +207 -0
- package/__tests__/features/adapter/adapter.progress.spec.ts +39 -0
- package/__tests__/features/adapter/adapter.responses.spec.ts +162 -1
- package/__tests__/features/adapter/adapter.server.spec.ts +6 -6
- package/__tests__/features/adapter/adapter.types.spec.ts +121 -2
- package/__tests__/features/adapter/adapter.utils.spec.ts +4 -2
- package/__tests__/features/adapter/adapter.variables.spec.ts +3 -3
- package/__tests__/features/socket/socket.connection.spec.ts +892 -0
- package/__tests__/features/socket/socket.fuzz.spec.ts +329 -0
- package/__tests__/features/socket/socket.subscriptions.spec.ts +515 -0
- package/__tests__/features/socket/socket.types.spec.ts +160 -0
- package/__tests__/utils/controlled-websocket.ts +238 -0
- package/dist/adapter/adapter.constants.d.ts +5 -0
- package/dist/adapter/adapter.constants.d.ts.map +1 -1
- package/dist/adapter/adapter.types.d.ts +55 -2
- package/dist/adapter/adapter.types.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts +51 -4
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +958 -128
- package/dist/index.mjs.map +1 -1
- package/dist/socket/index.d.ts +5 -0
- package/dist/socket/index.d.ts.map +1 -0
- package/dist/socket/socket.constants.d.ts +44 -0
- package/dist/socket/socket.constants.d.ts.map +1 -0
- package/dist/socket/socket.subscriptions.d.ts +74 -0
- package/dist/socket/socket.subscriptions.d.ts.map +1 -0
- package/dist/socket/socket.types.d.ts +102 -0
- package/dist/socket/socket.types.d.ts.map +1 -0
- package/dist/socket/socket.utils.d.ts +80 -0
- package/dist/socket/socket.utils.d.ts.map +1 -0
- package/dist/socket/socket.websocket.d.ts +30 -0
- package/dist/socket/socket.websocket.d.ts.map +1 -0
- package/package.json +14 -9
- package/src/adapter/adapter.constants.ts +6 -0
- package/src/adapter/adapter.types.ts +69 -3
- package/src/adapter/adapter.utils.ts +196 -25
- package/src/adapter/http-adapter.fetch.ts +93 -43
- package/src/index.ts +1 -0
- package/src/socket/index.ts +4 -0
- package/src/socket/socket.constants.ts +59 -0
- package/src/socket/socket.subscriptions.ts +160 -0
- package/src/socket/socket.types.ts +118 -0
- package/src/socket/socket.utils.ts +150 -0
- package/src/socket/socket.websocket.ts +555 -0
- package/vite.config.ts +4 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/graphql",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "10.1.0",
|
|
4
|
+
"description": "GraphQL adapters for Hyper Fetch - queries and mutations over HTTP, subscriptions over WebSocket",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|
|
7
7
|
"license": "Apache-2.0",
|
|
@@ -43,15 +43,16 @@
|
|
|
43
43
|
"url": "https://github.com/BetterTyped/hyper-fetch/issues"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
|
-
"@hyper-fetch/core": "*"
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
"events": "^3.3.0",
|
|
50
|
-
"graphql": "*"
|
|
46
|
+
"@hyper-fetch/core": "*",
|
|
47
|
+
"@hyper-fetch/sockets": "*",
|
|
48
|
+
"graphql": "^15.0.0 || ^16.0.0"
|
|
51
49
|
},
|
|
52
50
|
"devDependencies": {
|
|
53
51
|
"abortcontroller-polyfill": "^1.7.5",
|
|
54
|
-
"graphql
|
|
52
|
+
"graphql": "^16.13.2",
|
|
53
|
+
"graphql-tag": "^2.12.6",
|
|
54
|
+
"graphql-ws": "^6.0.0",
|
|
55
|
+
"ws": "^8.18.0"
|
|
55
56
|
},
|
|
56
57
|
"lint-staged": {
|
|
57
58
|
"*.{js,jsx,ts,tsx}": [
|
|
@@ -68,6 +69,10 @@
|
|
|
68
69
|
"gql",
|
|
69
70
|
"gql-request",
|
|
70
71
|
"gql-node",
|
|
71
|
-
"gql-browser"
|
|
72
|
+
"gql-browser",
|
|
73
|
+
"subscriptions",
|
|
74
|
+
"websocket",
|
|
75
|
+
"graphql-ws",
|
|
76
|
+
"graphql-transport-ws"
|
|
72
77
|
]
|
|
73
78
|
}
|
|
@@ -4,6 +4,12 @@ import type { GraphQlExtraType } from "./adapter.types";
|
|
|
4
4
|
|
|
5
5
|
export const defaultTimeout = Time.SEC * 5;
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* GraphQL over HTTP media type first, so spec compliant servers answer with meaningful status codes,
|
|
9
|
+
* and JSON as the fallback for the others.
|
|
10
|
+
*/
|
|
11
|
+
export const gqlAcceptHeader = "application/graphql-response+json, application/json;q=0.9";
|
|
12
|
+
|
|
7
13
|
export const gqlExtra: GraphQlExtraType = {
|
|
8
14
|
headers: {},
|
|
9
15
|
extensions: {},
|
|
@@ -1,4 +1,14 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
Adapter,
|
|
3
|
+
DefaultMapperType,
|
|
4
|
+
EmptyTypes,
|
|
5
|
+
ExtractEndpointPayloadType,
|
|
6
|
+
ExtractEndpointResponseType,
|
|
7
|
+
QueryParamsType,
|
|
8
|
+
RequestInstance,
|
|
9
|
+
stringifyQueryParams,
|
|
10
|
+
} from "@hyper-fetch/core";
|
|
11
|
+
import type { GraphQLFormattedError } from "graphql";
|
|
2
12
|
import type { DocumentNode } from "graphql/language/ast";
|
|
3
13
|
|
|
4
14
|
export enum GraphqlMethod {
|
|
@@ -6,14 +16,52 @@ export enum GraphqlMethod {
|
|
|
6
16
|
GET = "GET",
|
|
7
17
|
}
|
|
8
18
|
|
|
9
|
-
export type GraphQlExtraType = {
|
|
19
|
+
export type GraphQlExtraType = {
|
|
20
|
+
headers: HeadersInit;
|
|
21
|
+
extensions: Record<string, any>;
|
|
22
|
+
/**
|
|
23
|
+
* The `errors` of the response body, when the server sent any. With the `"all"` error policy a response with
|
|
24
|
+
* partial data succeeds, and this is where its errors are.
|
|
25
|
+
*/
|
|
26
|
+
errors?: GraphQLFormattedError[];
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* What a response that has both `data` and `errors` resolves to.
|
|
31
|
+
*
|
|
32
|
+
* - `"none"` - it fails: `data` is `null` and `error` holds the errors.
|
|
33
|
+
* - `"all"` - it succeeds with the partial `data`, and the errors are in `extra.errors`. A response without `data`
|
|
34
|
+
* still fails.
|
|
35
|
+
*/
|
|
36
|
+
export type GraphqlErrorPolicy = "none" | "all";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Error of a GraphQL request: the `errors` of the response body, or a single network, abort or timeout error.
|
|
40
|
+
* Pass it to the client to type `response.error` - `new Client<GraphqlErrorType>({ url })`.
|
|
41
|
+
*/
|
|
42
|
+
export type GraphqlErrorType = (GraphQLFormattedError | Error)[];
|
|
10
43
|
|
|
11
44
|
export type GraphQlEndpointType = string | DocumentNode;
|
|
12
45
|
|
|
13
46
|
export type FetchGraphqlAdapterOptionsType = Omit<RequestInit, "method" | "headers" | "body" | "signal"> & {
|
|
14
47
|
timeout?: number;
|
|
48
|
+
/**
|
|
49
|
+
* What a response with both `data` and `errors` resolves to. `"none"` fails it, `"all"` keeps the partial data.
|
|
50
|
+
* @default "none"
|
|
51
|
+
*/
|
|
52
|
+
errorPolicy?: GraphqlErrorPolicy;
|
|
53
|
+
/**
|
|
54
|
+
* Automatic persisted queries. The request sends the SHA-256 hash of the query instead of the query, and the full
|
|
55
|
+
* query only when the server does not know the hash yet. Hashed `GET` requests stay short, so CDNs can cache them.
|
|
56
|
+
* Without Web Crypto (`crypto.subtle`) the full query is sent.
|
|
57
|
+
* @default false
|
|
58
|
+
*/
|
|
59
|
+
persistedQueries?: boolean;
|
|
15
60
|
};
|
|
16
61
|
|
|
62
|
+
/** The `persistedQuery` extension of automatic persisted queries */
|
|
63
|
+
export type GraphqlPersistedQueryType = { version: 1; sha256Hash: string };
|
|
64
|
+
|
|
17
65
|
export type GraphqlRequestOptionsType = {
|
|
18
66
|
/**
|
|
19
67
|
* GraphQL document sent as `query`. When it is set, `endpoint` becomes a URL path appended to `client.url`,
|
|
@@ -22,6 +70,24 @@ export type GraphqlRequestOptionsType = {
|
|
|
22
70
|
document?: GraphQlEndpointType;
|
|
23
71
|
};
|
|
24
72
|
|
|
73
|
+
/**
|
|
74
|
+
* Response and payload of a typed document - a `TypedDocumentNode` from graphql-codegen or a gql.tada document.
|
|
75
|
+
* `createRequest` reads them from a typed document passed as `endpoint` by itself. Use this type when the document is
|
|
76
|
+
* passed with the `document` option, or to combine the document types with other request types.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* const getUser = client.createRequest<GraphqlDocumentTypes<typeof GetUserDocument>>()({
|
|
81
|
+
* endpoint: "/User",
|
|
82
|
+
* document: GetUserDocument,
|
|
83
|
+
* });
|
|
84
|
+
* ```
|
|
85
|
+
*/
|
|
86
|
+
export type GraphqlDocumentTypes<Document> = {
|
|
87
|
+
response: ExtractEndpointResponseType<Document>;
|
|
88
|
+
payload: ExtractEndpointPayloadType<Document>;
|
|
89
|
+
};
|
|
90
|
+
|
|
25
91
|
export type GraphqlAdapterType = Adapter<
|
|
26
92
|
FetchGraphqlAdapterOptionsType,
|
|
27
93
|
GraphqlMethod,
|
|
@@ -32,7 +98,7 @@ export type GraphqlAdapterType = Adapter<
|
|
|
32
98
|
GraphQlEndpointType,
|
|
33
99
|
(endpoint: GraphQlEndpointType) => string,
|
|
34
100
|
typeof stringifyQueryParams,
|
|
35
|
-
|
|
101
|
+
(request: RequestInstance) => HeadersInit,
|
|
36
102
|
DefaultMapperType,
|
|
37
103
|
GraphqlRequestOptionsType
|
|
38
104
|
>;
|
|
@@ -1,9 +1,39 @@
|
|
|
1
1
|
import type { EmptyTypes, QueryParamsType, RequestInstance } from "@hyper-fetch/core";
|
|
2
|
-
import { HttpMethods, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
|
|
2
|
+
import { getAdapterHeaders, HttpMethods, Request, stringifyKey, stringifyQueryParams } from "@hyper-fetch/core";
|
|
3
3
|
import type { DocumentNode, OperationDefinitionNode } from "graphql";
|
|
4
4
|
import { print, parse } from "graphql";
|
|
5
5
|
|
|
6
|
-
import type { GraphQlEndpointType, GraphqlRequestOptionsType } from "./adapter.types";
|
|
6
|
+
import type { GraphQlEndpointType, GraphqlPersistedQueryType, GraphqlRequestOptionsType } from "./adapter.types";
|
|
7
|
+
import { GraphqlMethod } from "./adapter.types";
|
|
8
|
+
|
|
9
|
+
/** Whether the request headers name the content type, also with an empty value that removes it */
|
|
10
|
+
const hasContentTypeHeader = (headers: HeadersInit | undefined) => {
|
|
11
|
+
if (!headers) return false;
|
|
12
|
+
const names =
|
|
13
|
+
typeof Headers !== "undefined" && headers instanceof Headers
|
|
14
|
+
? [...headers.keys()]
|
|
15
|
+
: (Array.isArray(headers) ? headers : Object.entries(headers)).map(([name]) => name);
|
|
16
|
+
return names.some((name) => name.toLowerCase() === "content-type");
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A POST body is always JSON (`query`, `operationName`, `variables`, `extensions`), also for an operation without
|
|
21
|
+
* variables, so it needs the JSON content type. A GET request has no body and sends the operation in the URL, so it
|
|
22
|
+
* gets none - the header would only trigger a CORS preflight. A content type given with the request always wins.
|
|
23
|
+
*/
|
|
24
|
+
export const getGqlHeaders = (request: RequestInstance): HeadersInit => {
|
|
25
|
+
const headers = { ...(getAdapterHeaders(request) as Record<string, string>) };
|
|
26
|
+
|
|
27
|
+
if (hasContentTypeHeader(request.headers)) {
|
|
28
|
+
return headers;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
delete headers["Content-Type"];
|
|
32
|
+
if (request.method === GraphqlMethod.POST) {
|
|
33
|
+
headers["Content-Type"] = "application/json";
|
|
34
|
+
}
|
|
35
|
+
return headers;
|
|
36
|
+
};
|
|
7
37
|
|
|
8
38
|
const getDocumentOption = (request: RequestInstance) => {
|
|
9
39
|
return (request.requestOptions as unknown as GraphqlRequestOptionsType).document;
|
|
@@ -17,13 +47,13 @@ export const getGqlDocument = (request: RequestInstance): GraphQlEndpointType =>
|
|
|
17
47
|
};
|
|
18
48
|
|
|
19
49
|
/** Query string keys owned by the GraphQL over HTTP GET format - they win over the user query params */
|
|
20
|
-
const reservedQueryParams = ["query", "variables"];
|
|
50
|
+
const reservedQueryParams = new Set(["query", "operationName", "variables", "extensions"]);
|
|
21
51
|
|
|
22
52
|
const isReservedQueryParam = (param: string) => {
|
|
23
53
|
const [rawKey] = param.split("=");
|
|
24
54
|
try {
|
|
25
55
|
// Array formats encode the key as `key[]` or `key[0]`
|
|
26
|
-
return reservedQueryParams.
|
|
56
|
+
return reservedQueryParams.has(decodeURIComponent(rawKey).split("[")[0]);
|
|
27
57
|
} catch {
|
|
28
58
|
return false;
|
|
29
59
|
}
|
|
@@ -46,14 +76,22 @@ const joinQueryStrings = (...queryStrings: string[]) => {
|
|
|
46
76
|
return joined ? `?${joined}` : "";
|
|
47
77
|
};
|
|
48
78
|
|
|
79
|
+
/**
|
|
80
|
+
* Url and body of the request in the GraphQL over HTTP format.
|
|
81
|
+
* With `persisted`, the `persistedQuery` extension is sent, and the query only when `withQuery` is set.
|
|
82
|
+
*/
|
|
49
83
|
export const getRequestValues = <R extends RequestInstance>(
|
|
50
84
|
request: R,
|
|
51
85
|
queryParams: unknown = request.client.adapter.unstable_queryParamsMapper(request.queryParams),
|
|
86
|
+
persisted?: { persistedQuery: GraphqlPersistedQueryType; withQuery: boolean },
|
|
52
87
|
) => {
|
|
53
88
|
const isPostRequest = request.method === HttpMethods.POST;
|
|
54
89
|
|
|
55
|
-
const
|
|
90
|
+
const document = getGqlDocument(request);
|
|
91
|
+
const query = !persisted || persisted.withQuery ? gqlEndpointMapper(document) : undefined;
|
|
92
|
+
const operationName = getGqlOperationName(document);
|
|
56
93
|
const variables = request.payload;
|
|
94
|
+
const extensions = persisted ? { persistedQuery: persisted.persistedQuery } : undefined;
|
|
57
95
|
|
|
58
96
|
const url = hasDocumentOption(request) ? `${request.client.url}${request.endpoint}` : request.client.url;
|
|
59
97
|
// Mappers can return anything, so we normalize their result to the query string
|
|
@@ -61,12 +99,18 @@ export const getRequestValues = <R extends RequestInstance>(
|
|
|
61
99
|
|
|
62
100
|
const fullUrl = isPostRequest
|
|
63
101
|
? url + joinQueryStrings(queryString)
|
|
64
|
-
: url +
|
|
102
|
+
: url +
|
|
103
|
+
joinQueryStrings(
|
|
104
|
+
stringifyQueryParams({ query, operationName, variables, extensions }),
|
|
105
|
+
omitReservedQueryParams(queryString),
|
|
106
|
+
);
|
|
65
107
|
|
|
66
108
|
const payload = isPostRequest
|
|
67
109
|
? JSON.stringify({
|
|
68
110
|
query,
|
|
111
|
+
operationName,
|
|
69
112
|
variables,
|
|
113
|
+
extensions,
|
|
70
114
|
})
|
|
71
115
|
: null;
|
|
72
116
|
|
|
@@ -80,10 +124,34 @@ export const gqlEndpointMapper = <E extends GraphQlEndpointType>(endpoint: E): s
|
|
|
80
124
|
return print(endpoint);
|
|
81
125
|
};
|
|
82
126
|
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
127
|
+
const findOperation = (ast: DocumentNode) => {
|
|
128
|
+
return ast.definitions.find((def): def is OperationDefinitionNode => def.kind === "OperationDefinition");
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const parseDocument = (document: GraphQlEndpointType): DocumentNode | undefined => {
|
|
132
|
+
if (typeof document !== "string") {
|
|
133
|
+
return document;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
return parse(document);
|
|
137
|
+
} catch {
|
|
138
|
+
// The server reports an invalid document, the name and the operationName are only a best effort
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Name of the first operation of the document, sent as `operationName`.
|
|
145
|
+
* Anonymous operations and documents that do not parse have none.
|
|
146
|
+
*/
|
|
147
|
+
export const getGqlOperationName = (document: GraphQlEndpointType): string | undefined => {
|
|
148
|
+
const ast = parseDocument(document);
|
|
149
|
+
|
|
150
|
+
return ast ? findOperation(ast)?.name?.value : undefined;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const getOperationLabel = (ast: DocumentNode): string | undefined => {
|
|
154
|
+
const operationDefinition = findOperation(ast);
|
|
87
155
|
|
|
88
156
|
if (operationDefinition) {
|
|
89
157
|
if (operationDefinition.name?.value) {
|
|
@@ -102,19 +170,17 @@ const getOperationName = (ast: DocumentNode): string | undefined => {
|
|
|
102
170
|
return undefined;
|
|
103
171
|
};
|
|
104
172
|
|
|
173
|
+
/** Readable name of the document - the operation name or, for anonymous operations, the first selected field */
|
|
105
174
|
export const gqlEndpointNameMapper = (endpoint: GraphQlEndpointType): string => {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
}
|
|
175
|
+
const ast = parseDocument(endpoint);
|
|
176
|
+
const name = ast ? getOperationLabel(ast) : undefined;
|
|
109
177
|
|
|
110
|
-
|
|
111
|
-
|
|
178
|
+
if (name) {
|
|
179
|
+
return name;
|
|
180
|
+
}
|
|
112
181
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
} catch {
|
|
117
|
-
// We can ignore this error and just return some fallback
|
|
182
|
+
if (typeof endpoint !== "string") {
|
|
183
|
+
return "graphql-request";
|
|
118
184
|
}
|
|
119
185
|
|
|
120
186
|
// Fallback for invalid gql queries or something else
|
|
@@ -122,9 +188,42 @@ export const gqlEndpointNameMapper = (endpoint: GraphQlEndpointType): string =>
|
|
|
122
188
|
.replace(/(query|mutation|subscription)/, "")
|
|
123
189
|
.replaceAll(/[{}().,:]/g, " ")
|
|
124
190
|
.trim();
|
|
125
|
-
const [
|
|
191
|
+
const [fallbackName] = clearedQuery.split(" ");
|
|
126
192
|
|
|
127
|
-
return
|
|
193
|
+
return fallbackName || "graphql-request";
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/** FNV-1a - a short and stable fingerprint of a text */
|
|
197
|
+
const hashText = (text: string): string => {
|
|
198
|
+
let hash = 2_166_136_261; // FNV offset basis
|
|
199
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
200
|
+
// Code units, not code points - the loop walks every UTF-16 unit once
|
|
201
|
+
// eslint-disable-next-line unicorn/prefer-code-point
|
|
202
|
+
hash ^= text.charCodeAt(index);
|
|
203
|
+
hash = Math.imul(hash, 16_777_619); // FNV prime
|
|
204
|
+
}
|
|
205
|
+
// `>>> 0` reads the 32 bits as unsigned, `Math.trunc` would keep the sign
|
|
206
|
+
// eslint-disable-next-line unicorn/prefer-math-trunc
|
|
207
|
+
return (hash >>> 0).toString(36);
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
/** Printing a DocumentNode is the costly part, and gql documents are created once, so their fingerprint is kept */
|
|
211
|
+
const documentNodeHashes = new WeakMap<DocumentNode, string>();
|
|
212
|
+
|
|
213
|
+
/** Fingerprint of the document text sent as `query`. Documents with other selections get other fingerprints. */
|
|
214
|
+
const getDocumentHash = (document: GraphQlEndpointType): string => {
|
|
215
|
+
if (typeof document === "string") {
|
|
216
|
+
return hashText(document);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const known = documentNodeHashes.get(document);
|
|
220
|
+
if (known) {
|
|
221
|
+
return known;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const hash = hashText(print(document));
|
|
225
|
+
documentNodeHashes.set(document, hash);
|
|
226
|
+
return hash;
|
|
128
227
|
};
|
|
129
228
|
|
|
130
229
|
/**
|
|
@@ -138,12 +237,84 @@ export const gqlRequestNameMapper = (request: RequestInstance): string => {
|
|
|
138
237
|
};
|
|
139
238
|
|
|
140
239
|
/**
|
|
141
|
-
* Cache and query key of a request. The variables are a part of it:
|
|
142
|
-
*
|
|
240
|
+
* Cache and query key of a request. The document fingerprint and the variables are a part of it: two documents with
|
|
241
|
+
* one operation name but other selections, or the same operation with other variables, are other queries - with their
|
|
242
|
+
* own cached data and their own place in the queue.
|
|
143
243
|
*/
|
|
144
244
|
export const gqlRequestKeyMapper = (request: RequestInstance): string => {
|
|
145
|
-
const
|
|
245
|
+
const name = `${gqlRequestNameMapper(request)}@${getDocumentHash(getGqlDocument(request))}`;
|
|
246
|
+
const key = `${request.method}_${name}-${stringifyKey(request.params)}-${stringifyKey(request.queryParams)}`;
|
|
146
247
|
const variables = stringifyKey(request.payload);
|
|
147
248
|
|
|
148
249
|
return variables ? `${key}-${variables}` : key;
|
|
149
250
|
};
|
|
251
|
+
|
|
252
|
+
const escapeRegExp = (text: string) => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`);
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Matches the cache keys of every request of a GraphQL operation - with any variables, params, query params and
|
|
256
|
+
* method. Pass it to `client.cache.invalidate()` after a mutation, so the active queries of the operation refetch, like
|
|
257
|
+
* `refetchQueries` in Apollo.
|
|
258
|
+
*
|
|
259
|
+
* - A document matches its requests on every url path of the `document` option.
|
|
260
|
+
* - A request matches the requests of its document on its own url path.
|
|
261
|
+
* - Documents with the same operation name but other selections are other operations, they do not match.
|
|
262
|
+
*
|
|
263
|
+
* @example
|
|
264
|
+
* ```ts
|
|
265
|
+
* await updateUser.send({ payload: { id: "1", name: "Ann" } });
|
|
266
|
+
* client.cache.invalidate(matchGqlOperation(GetUserDocument));
|
|
267
|
+
* ```
|
|
268
|
+
*/
|
|
269
|
+
export const matchGqlOperation = (operation: GraphQlEndpointType | RequestInstance): RegExp => {
|
|
270
|
+
if (operation instanceof Request) {
|
|
271
|
+
const name = escapeRegExp(gqlRequestNameMapper(operation));
|
|
272
|
+
return new RegExp(`^[A-Z]+_${name}@${getDocumentHash(getGqlDocument(operation))}-`);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const name = escapeRegExp(gqlEndpointNameMapper(operation));
|
|
276
|
+
// The path of the `document` option follows the name and never holds the fingerprint separator
|
|
277
|
+
return new RegExp(`^[A-Z]+_${name}(?:/[^@]*)?@${getDocumentHash(operation)}-`);
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* SHA-256 hash of the query for automatic persisted queries, as lowercase hex.
|
|
282
|
+
* `null` when the runtime has no working Web Crypto - the full query is sent then.
|
|
283
|
+
*/
|
|
284
|
+
export const getPersistedQueryHash = async (query: string): Promise<string | null> => {
|
|
285
|
+
const subtle = globalThis.crypto?.subtle;
|
|
286
|
+
if (!subtle) {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
const digest = await subtle.digest("SHA-256", new TextEncoder().encode(query));
|
|
292
|
+
return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
293
|
+
} catch {
|
|
294
|
+
// A runtime that refuses the digest is one without working Web Crypto - the full query is sent instead
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* How the server answered a hashed request it could not run: it does not know the hash yet (`"not-found"`), or it does
|
|
301
|
+
* not support persisted queries (`"not-supported"`). `null` for every other response. Servers report it by the message
|
|
302
|
+
* or by the error code.
|
|
303
|
+
*/
|
|
304
|
+
export const getPersistedQueryMiss = (body: unknown): "not-found" | "not-supported" | null => {
|
|
305
|
+
const errors: unknown[] = Array.isArray((body as { errors?: unknown })?.errors)
|
|
306
|
+
? (body as { errors: unknown[] }).errors
|
|
307
|
+
: [];
|
|
308
|
+
|
|
309
|
+
for (const error of errors) {
|
|
310
|
+
const { message, extensions } = (error ?? {}) as { message?: unknown; extensions?: { code?: unknown } };
|
|
311
|
+
if (message === "PersistedQueryNotSupported" || extensions?.code === "PERSISTED_QUERY_NOT_SUPPORTED") {
|
|
312
|
+
return "not-supported";
|
|
313
|
+
}
|
|
314
|
+
if (message === "PersistedQueryNotFound" || extensions?.code === "PERSISTED_QUERY_NOT_FOUND") {
|
|
315
|
+
return "not-found";
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return null;
|
|
320
|
+
};
|