forked from apollographql/apollo-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
264 lines (231 loc) · 8.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { invariant } from '../../utilities/globals';
import { print } from 'graphql';
import {
DocumentNode,
ExecutionResult,
GraphQLError,
} from 'graphql';
import { ApolloLink, Operation } from '../core';
import { Observable, Observer, compact } from '../../utilities';
export const VERSION = 1;
export interface ErrorResponse {
graphQLErrors?: readonly GraphQLError[];
networkError?: Error;
response?: ExecutionResult;
operation: Operation;
}
type SHA256Function = (...args: any[]) => string | PromiseLike<string>;
type GenerateHashFunction = (document: DocumentNode) => string | PromiseLike<string>;
export namespace PersistedQueryLink {
interface BaseOptions {
disable?: (error: ErrorResponse) => boolean;
useGETForHashedQueries?: boolean;
};
interface SHA256Options extends BaseOptions {
sha256: SHA256Function;
generateHash?: never;
};
interface GenerateHashOptions extends BaseOptions {
sha256?: never;
generateHash: GenerateHashFunction;
};
export type Options = SHA256Options | GenerateHashOptions;
}
const defaultOptions = {
disable: ({ graphQLErrors, operation }: ErrorResponse) => {
// if the server doesn't support persisted queries, don't try anymore
if (
graphQLErrors &&
graphQLErrors.some(
({ message }) => message === 'PersistedQueryNotSupported',
)
) {
return true;
}
const { response } = operation.getContext();
// if the server responds with bad request
// apollo-server responds with 400 for GET and 500 for POST when no query is found
if (
response &&
response.status &&
(response.status === 400 || response.status === 500)
) {
return true;
}
return false;
},
useGETForHashedQueries: false,
};
function operationDefinesMutation(operation: Operation) {
return operation.query.definitions.some(
d => d.kind === 'OperationDefinition' && d.operation === 'mutation');
}
const { hasOwnProperty } = Object.prototype;
const hashesByQuery = new WeakMap<
DocumentNode,
Record<string, Promise<string>>
>();
let nextHashesChildKey = 0;
export const createPersistedQueryLink = (
options: PersistedQueryLink.Options,
) => {
// Ensure a SHA-256 hash function is provided, if a custom hash
// generation function is not provided. We don't supply a SHA-256 hash
// function by default, to avoid forcing one as a dependency. Developers
// should pick the most appropriate SHA-256 function (sync or async) for
// their needs/environment, or provide a fully custom hash generation
// function (via the `generateHash` option) if they want to handle
// hashing with something other than SHA-256.
invariant(
options && (
typeof options.sha256 === 'function' ||
typeof options.generateHash === 'function'
),
'Missing/invalid "sha256" or "generateHash" function. Please ' +
'configure one using the "createPersistedQueryLink(options)" options ' +
'parameter.'
);
const {
sha256,
// If both a `sha256` and `generateHash` option are provided, the
// `sha256` option will be ignored. Developers can configure and
// use any hashing approach they want in a custom `generateHash`
// function; they aren't limited to SHA-256.
generateHash = (query: DocumentNode) =>
Promise.resolve<string>(sha256!(print(query))),
disable,
useGETForHashedQueries
} = compact(defaultOptions, options);
let supportsPersistedQueries = true;
const hashesChildKey = 'forLink' + nextHashesChildKey++;
const getHashPromise = (query: DocumentNode) =>
new Promise<string>(resolve => resolve(generateHash(query)));
function getQueryHash(query: DocumentNode): Promise<string> {
if (!query || typeof query !== 'object') {
// If the query is not an object, we won't be able to store its hash as
// a property of query[hashesKey], so we let generateHash(query) decide
// what to do with the bogus query.
return getHashPromise(query);
}
let hashes = hashesByQuery.get(query)!;
if (!hashes) hashesByQuery.set(query, hashes = Object.create(null));
return hasOwnProperty.call(hashes, hashesChildKey)
? hashes[hashesChildKey]
: hashes[hashesChildKey] = getHashPromise(query);
}
return new ApolloLink((operation, forward) => {
invariant(
forward,
'PersistedQueryLink cannot be the last link in the chain.'
);
const { query } = operation;
return new Observable((observer: Observer<ExecutionResult>) => {
let subscription: ZenObservable.Subscription;
let retried = false;
let originalFetchOptions: any;
let setFetchOptions = false;
const retry = (
{
response,
networkError,
}: { response?: ExecutionResult; networkError?: Error },
cb: () => void,
) => {
if (!retried && ((response && response.errors) || networkError)) {
retried = true;
const disablePayload = {
response,
networkError,
operation,
graphQLErrors: response ? response.errors : undefined,
};
// if the server doesn't support persisted queries, don't try anymore
supportsPersistedQueries = !disable(disablePayload);
// if its not found, we can try it again, otherwise just report the error
if (
(response &&
response.errors &&
response.errors.some(
({ message }: { message: string }) =>
message === 'PersistedQueryNotFound',
)) ||
!supportsPersistedQueries
) {
// need to recall the link chain
if (subscription) subscription.unsubscribe();
// actually send the query this time
operation.setContext({
http: {
includeQuery: true,
includeExtensions: supportsPersistedQueries,
},
fetchOptions: {
// Since we're including the full query, which may be
// large, we should send it in the body of a POST request.
// See issue #7456.
method: 'POST',
},
});
if (setFetchOptions) {
operation.setContext({ fetchOptions: originalFetchOptions });
}
subscription = forward(operation).subscribe(handler);
return;
}
}
cb();
};
const handler = {
next: (response: ExecutionResult) => {
retry({ response }, () => observer.next!(response));
},
error: (networkError: Error) => {
retry({ networkError }, () => observer.error!(networkError));
},
complete: observer.complete!.bind(observer),
};
// don't send the query the first time
operation.setContext({
http: {
includeQuery: !supportsPersistedQueries,
includeExtensions: supportsPersistedQueries,
},
});
// If requested, set method to GET if there are no mutations. Remember the
// original fetchOptions so we can restore them if we fall back to a
// non-hashed request.
if (
useGETForHashedQueries &&
supportsPersistedQueries &&
!operationDefinesMutation(operation)
) {
operation.setContext(
({ fetchOptions = {} }: { fetchOptions: Record<string, any> }) => {
originalFetchOptions = fetchOptions;
return {
fetchOptions: {
...fetchOptions,
method: 'GET',
},
};
},
);
setFetchOptions = true;
}
if (supportsPersistedQueries) {
getQueryHash(query).then((sha256Hash) => {
operation.extensions.persistedQuery = {
version: VERSION,
sha256Hash,
};
subscription = forward(operation).subscribe(handler);
}).catch(observer.error!.bind(observer));;
} else {
subscription = forward(operation).subscribe(handler);
}
return () => {
if (subscription) subscription.unsubscribe();
};
});
});
};