-
Notifications
You must be signed in to change notification settings - Fork 36
/
WrappedApolloClient.tsx
393 lines (352 loc) · 12.7 KB
/
WrappedApolloClient.tsx
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/* eslint-disable prefer-rest-params */
import type {
ApolloClientOptions,
OperationVariables,
WatchQueryOptions,
FetchResult,
DocumentNode,
NormalizedCacheObject,
} from "@apollo/client/index.js";
import {
ApolloClient as OrigApolloClient,
Observable,
} from "@apollo/client/index.js";
import type { QueryManager } from "@apollo/client/core/QueryManager.js";
import { print } from "@apollo/client/utilities/index.js";
import { canonicalStringify } from "@apollo/client/cache/index.js";
import { invariant } from "ts-invariant";
import { createBackpressuredCallback } from "./backpressuredCallback.js";
import type { InMemoryCache } from "./WrappedInMemoryCache.js";
import { hookWrappers } from "./hooks.js";
import type { HookWrappers } from "@apollo/client/react/internal/index.js";
import type { QueryInfo } from "@apollo/client/core/QueryInfo.js";
import type {
ProgressEvent,
QueryEvent,
TransportIdentifier,
} from "./DataTransportAbstraction.js";
import { bundle, sourceSymbol } from "../bundleInfo.js";
import { serializeOptions, deserializeOptions } from "./transportedOptions.js";
import { assertInstance } from "../assertInstance.js";
function getQueryManager(
client: OrigApolloClient<unknown>
): QueryManager<NormalizedCacheObject> & {
[wrappers]: HookWrappers;
} {
return client["queryManager"];
}
/**
* Returns the `Trie` constructor without adding a direct dependency on `@wry/trie`.
*/
function getTrieConstructor(client: OrigApolloClient<unknown>) {
return getQueryManager(client)["inFlightLinkObservables"]
.constructor as typeof import("@wry/trie").Trie;
}
type SimulatedQueryInfo = {
resolve: (result: FetchResult) => void;
reject: (reason: any) => void;
options: WatchQueryOptions<OperationVariables, any>;
};
interface WrappedApolloClientOptions
extends Omit<ApolloClientOptions<NormalizedCacheObject>, "cache"> {
cache: InMemoryCache;
}
const wrappers = Symbol.for("apollo.hook.wrappers");
class ApolloClientBase extends OrigApolloClient<NormalizedCacheObject> {
/**
* Information about the current package and it's export names, for use in error messages.
*
* @internal
*/
static readonly info = bundle;
[sourceSymbol]: string;
constructor(options: WrappedApolloClientOptions) {
super(
process.env.REACT_ENV === "rsc" || process.env.REACT_ENV === "ssr"
? {
connectToDevTools: false,
...options,
}
: options
);
const info = (this.constructor as typeof ApolloClientBase).info;
this[sourceSymbol] = `${info.pkg}:ApolloClient`;
assertInstance(
this.cache as unknown as InMemoryCache,
info,
"InMemoryCache"
);
}
}
export class ApolloClientClientBaseImpl extends ApolloClientBase {
constructor(options: WrappedApolloClientOptions) {
super(options);
this.onQueryStarted = this.onQueryStarted.bind(this);
getQueryManager(this)[wrappers] = hookWrappers;
}
private simulatedStreamingQueries = new Map<
TransportIdentifier,
SimulatedQueryInfo
>();
private transportedQueryOptions = new Map<
TransportIdentifier,
WatchQueryOptions
>();
protected identifyUniqueQuery(options: {
query: DocumentNode;
variables?: unknown;
}) {
const transformedDocument = this.documentTransform.transformDocument(
options.query
);
const queryManager = getQueryManager(this);
// Calling `transformDocument` will add __typename but won't remove client
// directives, so we need to get the `serverQuery`.
const { serverQuery } = queryManager.getDocumentInfo(transformedDocument);
if (!serverQuery) {
throw new Error("could not identify unique query");
}
const canonicalVariables = canonicalStringify(options.variables || {});
const cacheKeyArr = [print(serverQuery), canonicalVariables];
const cacheKey = JSON.stringify(cacheKeyArr);
return {
cacheKey,
cacheKeyArr,
};
}
onQueryStarted({ options, id }: Extract<QueryEvent, { type: "started" }>) {
const hydratedOptions = deserializeOptions(options);
const { cacheKey, cacheKeyArr } = this.identifyUniqueQuery(hydratedOptions);
this.transportedQueryOptions.set(id, hydratedOptions);
const queryManager = getQueryManager(this);
if (
!queryManager["inFlightLinkObservables"].peekArray(cacheKeyArr)
?.observable
) {
let simulatedStreamingQuery: SimulatedQueryInfo,
fetchCancelFn: (reason: unknown) => void;
const cleanup = () => {
if (queryManager["fetchCancelFns"].get(cacheKey) === fetchCancelFn)
queryManager["fetchCancelFns"].delete(cacheKey);
queryManager["inFlightLinkObservables"].removeArray(cacheKeyArr);
if (this.simulatedStreamingQueries.get(id) === simulatedStreamingQuery)
this.simulatedStreamingQueries.delete(id);
};
const promise = new Promise<FetchResult>((resolve, reject) => {
this.simulatedStreamingQueries.set(
id,
(simulatedStreamingQuery = {
resolve,
reject,
options: hydratedOptions,
})
);
});
promise.then(cleanup, cleanup);
const observable = new Observable<FetchResult>((observer) => {
promise
.then((result) => {
observer.next(result);
observer.complete();
})
.catch((err) => {
observer.error(err);
});
});
queryManager["inFlightLinkObservables"].lookupArray(
cacheKeyArr
).observable = observable;
queryManager["fetchCancelFns"].set(
cacheKey,
(fetchCancelFn = (reason: unknown) => {
const { reject } = this.simulatedStreamingQueries.get(id) ?? {};
if (reject) {
reject(reason);
}
cleanup();
})
);
}
}
onQueryProgress = (event: ProgressEvent) => {
const queryInfo = this.simulatedStreamingQueries.get(event.id);
if (event.type === "data") {
queryInfo?.resolve?.({
data: event.result.data,
});
// In order to avoid a scenario where the promise resolves without
// a query subscribing to the promise, we immediately call
// `cache.write` here.
// For more information, see: https://github.com/apollographql/apollo-client-nextjs/pull/38/files/388813a16e2ac5c62408923a1face9ae9417d92a#r1229870523
const options = this.transportedQueryOptions.get(event.id);
if (options) {
this.cache.writeQuery({
query: options.query,
data: event.result.data,
variables: options.variables,
});
}
} else if (event.type === "error") {
/**
* At this point we're not able to correctly serialize the error over the wire
* so we do the next-best thing: restart the query in the browser as soon as it
* failed on the server.
* This matches up with what React will be doing (abort hydration and rerender)
* See https://github.com/apollographql/apollo-client-nextjs/issues/52
*/
if (queryInfo) {
this.simulatedStreamingQueries.delete(event.id);
if (process.env.REACT_ENV === "browser") {
invariant.debug(
"Query failed on server, rerunning in browser:",
queryInfo.options
);
this.rerunSimulatedQuery(queryInfo);
} else if (process.env.REACT_ENV === "ssr") {
invariant.debug(
"Query failed upstream, will fail it during SSR and rerun it in the browser:",
queryInfo.options
);
queryInfo?.reject?.(new Error("Query failed upstream."));
}
}
this.transportedQueryOptions.delete(event.id);
} else if (event.type === "complete") {
this.transportedQueryOptions.delete(event.id);
}
};
/**
* Can be called when the stream closed unexpectedly while there might still be unresolved
* simulated server-side queries going on.
* Those queries will be cancelled and then re-run in the browser.
*/
rerunSimulatedQueries = () => {
for (const [id, queryInfo] of this.simulatedStreamingQueries) {
this.simulatedStreamingQueries.delete(id);
invariant.debug(
"streaming connection closed before server query could be fully transported, rerunning:",
queryInfo.options
);
this.rerunSimulatedQuery(queryInfo);
}
};
rerunSimulatedQuery = (queryInfo: SimulatedQueryInfo) => {
const queryManager = getQueryManager(this);
const queryId = queryManager.generateQueryId();
queryManager
.fetchQuery(queryId, {
...queryInfo.options,
query: queryManager.transform(queryInfo.options.query),
context: {
...queryInfo.options.context,
queryDeduplication: false,
},
})
.finally(() => queryManager.stopQuery(queryId))
.then(queryInfo.resolve, queryInfo.reject);
};
}
class ApolloClientSSRImpl extends ApolloClientClientBaseImpl {
private forwardedQueries = new (getTrieConstructor(this))();
watchQueryQueue = createBackpressuredCallback<{
event: Extract<QueryEvent, { type: "started" }>;
observable: Observable<Exclude<QueryEvent, { type: "started" }>>;
}>();
watchQuery<
T = any,
TVariables extends OperationVariables = OperationVariables,
>(options: WatchQueryOptions<TVariables, T>) {
const { cacheKeyArr } = this.identifyUniqueQuery(options);
if (
options.fetchPolicy !== "cache-only" &&
options.fetchPolicy !== "standby" &&
!this.forwardedQueries.peekArray(cacheKeyArr)
) {
// don't transport the same query over twice
this.forwardedQueries.lookupArray(cacheKeyArr);
const observableQuery = super.watchQuery(options);
const queryInfo = observableQuery["queryInfo"] as QueryInfo;
const id = queryInfo.queryId as TransportIdentifier;
const streamObservable = new Observable<
Exclude<QueryEvent, { type: "started" }>
>((subscriber) => {
const { markResult, markError, markReady } = queryInfo;
queryInfo.markResult = function (result: FetchResult<any>) {
subscriber.next({
type: "data",
id,
result,
});
return markResult.apply(queryInfo, arguments as any);
};
queryInfo.markError = function () {
subscriber.next({
type: "error",
id,
});
subscriber.complete();
return markError.apply(queryInfo, arguments as any);
};
queryInfo.markReady = function () {
subscriber.next({
type: "complete",
id,
});
subscriber.complete();
return markReady.apply(queryInfo, arguments as any);
};
});
this.watchQueryQueue.push({
event: {
type: "started",
options: serializeOptions(options),
id,
},
observable: streamObservable,
});
return observableQuery;
}
return super.watchQuery(options);
}
onQueryStarted(event: Extract<QueryEvent, { type: "started" }>) {
const hydratedOptions = deserializeOptions(event.options);
const { cacheKeyArr } = this.identifyUniqueQuery(hydratedOptions);
// this is a replay from another source and doesn't need to be transported
// to the browser, since it will be replayed there, too.
this.forwardedQueries.lookupArray(cacheKeyArr);
super.onQueryStarted(event);
}
}
export class ApolloClientBrowserImpl extends ApolloClientClientBaseImpl {}
const ApolloClientImplementation =
/*#__PURE__*/ process.env.REACT_ENV === "ssr"
? ApolloClientSSRImpl
: process.env.REACT_ENV === "browser"
? ApolloClientBrowserImpl
: ApolloClientBase;
/**
* A version of `ApolloClient` to be used with streaming SSR or in React Server Components.
*
* For more documentation, please see {@link https://www.apollographql.com/docs/react/api/core/ApolloClient | the Apollo Client API documentation}.
*
* @public
*/
export class ApolloClient<
// this generic is obsolete as we require a `InMemoryStore`, which fixes this generic to `NormalizedCacheObject` anyways
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Ignored = NormalizedCacheObject,
>
extends (ApolloClientImplementation as typeof ApolloClientBase)
implements Partial<ApolloClientBrowserImpl>, Partial<ApolloClientSSRImpl>
{
/** @internal */
declare onQueryStarted?: ApolloClientBrowserImpl["onQueryStarted"];
/** @internal */
declare onQueryProgress?: ApolloClientBrowserImpl["onQueryProgress"];
/** @internal */
declare rerunSimulatedQueries?: ApolloClientBrowserImpl["rerunSimulatedQueries"];
/** @internal */
declare rerunSimulatedQuery?: ApolloClientBrowserImpl["rerunSimulatedQuery"];
/** @internal */
declare watchQueryQueue?: ApolloClientSSRImpl["watchQueryQueue"];
}