-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathQueryReference.ts
203 lines (164 loc) · 5.29 KB
/
QueryReference.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
import type {
ApolloError,
ApolloQueryResult,
ObservableQuery,
OperationVariables,
WatchQueryOptions,
} from '../../core';
import { NetworkStatus, isNetworkRequestSettled } from '../../core';
import type { ObservableSubscription } from '../../utilities';
import { createFulfilledPromise, createRejectedPromise } from '../../utilities';
import type { CacheKey } from './types';
type Listener<TData> = (promise: Promise<ApolloQueryResult<TData>>) => void;
type FetchMoreOptions<TData> = Parameters<
ObservableQuery<TData>['fetchMore']
>[0];
interface QueryReferenceOptions {
key: CacheKey;
onDispose?: () => void;
autoDisposeTimeoutMs?: number;
}
export class QueryReference<TData = unknown> {
public result: ApolloQueryResult<TData>;
public readonly key: CacheKey;
public readonly observable: ObservableQuery<TData>;
public promiseCache?: Map<any[], Promise<ApolloQueryResult<TData>>>;
public promise: Promise<ApolloQueryResult<TData>>;
private subscription: ObservableSubscription;
private listeners = new Set<Listener<TData>>();
private autoDisposeTimeoutId: NodeJS.Timeout;
private initialized = false;
private refetching = false;
private resolve: ((result: ApolloQueryResult<TData>) => void) | undefined;
private reject: ((error: unknown) => void) | undefined;
constructor(
observable: ObservableQuery<TData>,
options: QueryReferenceOptions
) {
this.listen = this.listen.bind(this);
this.handleNext = this.handleNext.bind(this);
this.handleError = this.handleError.bind(this);
this.dispose = this.dispose.bind(this);
this.observable = observable;
this.result = observable.getCurrentResult(false);
this.key = options.key;
if (options.onDispose) {
this.onDispose = options.onDispose;
}
if (
isNetworkRequestSettled(this.result.networkStatus) ||
(this.result.data &&
(!this.result.partial || this.observable.options.returnPartialData))
) {
this.promise = createFulfilledPromise(this.result);
this.initialized = true;
this.refetching = false;
}
this.subscription = observable.subscribe({
next: this.handleNext,
error: this.handleError,
});
if (!this.promise) {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
// Start a timer that will automatically dispose of the query if the
// suspended resource does not use this queryRef in the given time. This
// helps prevent memory leaks when a component has unmounted before the
// query has finished loading.
this.autoDisposeTimeoutId = setTimeout(
this.dispose,
options.autoDisposeTimeoutMs ?? 30_000
);
}
get watchQueryOptions() {
return this.observable.options;
}
listen(listener: Listener<TData>) {
// As soon as the component listens for updates, we know it has finished
// suspending and is ready to receive updates, so we can remove the auto
// dispose timer.
clearTimeout(this.autoDisposeTimeoutId);
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
refetch(variables: OperationVariables | undefined) {
this.refetching = true;
const promise = this.observable.refetch(variables);
this.promise = promise;
return promise;
}
fetchMore(options: FetchMoreOptions<TData>) {
const promise = this.observable.fetchMore<TData>(options);
this.promise = promise;
return promise;
}
reobserve(
watchQueryOptions: Partial<WatchQueryOptions<OperationVariables, TData>>
) {
const promise = this.observable.reobserve(watchQueryOptions);
this.promise = promise;
return promise;
}
dispose() {
this.subscription.unsubscribe();
this.onDispose();
}
private onDispose() {
// noop. overridable by options
}
private handleNext(result: ApolloQueryResult<TData>) {
if (!this.initialized || this.refetching) {
if (!isNetworkRequestSettled(result.networkStatus)) {
return;
}
// If we encounter an error with the new result after we have successfully
// fetched a previous result, set the new result data to the last successful
// result.
if (this.result.data && result.data === void 0) {
result.data = this.result.data;
}
this.initialized = true;
this.refetching = false;
this.result = result;
if (this.resolve) {
this.resolve(result);
}
return;
}
if (result.data === this.result.data) {
return;
}
this.result = result;
this.promise = createFulfilledPromise(result);
this.deliver(this.promise);
}
private handleError(error: ApolloError) {
const result = {
...this.result,
error,
networkStatus: NetworkStatus.error,
};
this.result = result;
if (!this.initialized || this.refetching) {
this.initialized = true;
this.refetching = false;
if (this.reject) {
this.reject(error);
}
return;
}
this.result = result;
this.promise = result.data
? createFulfilledPromise(result)
: createRejectedPromise(result);
this.deliver(this.promise);
}
private deliver(promise: Promise<ApolloQueryResult<TData>>) {
this.listeners.forEach((listener) => listener(promise));
}
}