This repository has been archived by the owner on Jan 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathindex.ts
227 lines (203 loc) · 6.5 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
import { ApolloLink, Observable, Operation } from 'apollo-link';
const sha256 = require('hash.js/lib/hash/sha/256');
import { print } from 'graphql/language/printer';
import {
DefinitionNode,
DocumentNode,
ExecutionResult,
GraphQLError,
} from 'graphql';
export const VERSION = 1;
export interface ErrorResponse {
graphQLErrors?: GraphQLError[];
networkError?: Error;
response?: ExecutionResult;
operation: Operation;
}
namespace PersistedQueryLink {
export type Options = {
generateHash?: (document: DocumentNode) => string;
disable?: (error: ErrorResponse) => boolean;
useGETForHashedQueries?: boolean;
};
}
export const defaultGenerateHash = (query: DocumentNode): string =>
sha256()
.update(print(query))
.digest('hex');
export const defaultOptions = {
generateHash: defaultGenerateHash,
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 definitionIsMutation(d: DefinitionNode) {
return d.kind === 'OperationDefinition' && d.operation === 'mutation';
}
// Note that this also returns true for subscriptions.
function operationIsQuery(operation: Operation) {
return !operation.query.definitions.some(definitionIsMutation);
}
const { hasOwnProperty } = Object.prototype;
const hashesKeyString = '__createPersistedQueryLink_hashes';
const hashesKey =
typeof Symbol === 'function' ? Symbol.for(hashesKeyString) : hashesKeyString;
let nextHashesChildKey = 0;
export const createPersistedQueryLink = (
options: PersistedQueryLink.Options = {},
) => {
const { generateHash, disable, useGETForHashedQueries } = Object.assign(
{},
defaultOptions,
options,
);
let supportsPersistedQueries = true;
const hashesChildKey = 'forLink' + nextHashesChildKey++;
function getQueryHash(query: DocumentNode): 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 generateHash(query);
}
if (!hasOwnProperty.call(query, hashesKey)) {
Object.defineProperty(query, hashesKey, {
value: Object.create(null),
enumerable: false,
});
}
const hashes = (query as any)[hashesKey];
return hasOwnProperty.call(hashes, hashesChildKey)
? hashes[hashesChildKey]
: (hashes[hashesChildKey] = generateHash(query));
}
return new ApolloLink((operation, forward) => {
if (!forward) {
throw new Error(
'PersistedQueryLink cannot be the last link in the chain.',
);
}
const { query } = operation;
let hashError: any;
if (supportsPersistedQueries) {
try {
operation.extensions.persistedQuery = {
version: VERSION,
sha256Hash: getQueryHash(query),
};
} catch (e) {
hashError = e;
}
}
return new Observable(observer => {
if (hashError) {
observer.error(hashError);
return;
}
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;
// if the server doesn't support persisted queries, don't try anymore
supportsPersistedQueries = !disable({
response,
networkError,
operation,
graphQLErrors:
(response && (response.errors as GraphQLError[])) || void 0,
});
// if its not found, we can try it again, otherwise just report the error
if (
(response &&
response.errors &&
response.errors.some(
({ message }) => 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,
},
});
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 &&
operationIsQuery(operation)
) {
operation.setContext(({ fetchOptions = {} }) => {
originalFetchOptions = fetchOptions;
return {
fetchOptions: Object.assign({}, fetchOptions, { method: 'GET' }),
};
});
setFetchOptions = true;
}
subscription = forward(operation).subscribe(handler);
return () => {
if (subscription) subscription.unsubscribe();
};
});
});
};