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 | 27x
27x
27x
27x
27x
27x
213x
1704x
771x
1704x
374x
374x
27x
27x
27x
173x
173x
173x
173x
173x
27x
27x
26x
26x
26x
24x
2x
24x
24x
24x
27x
121x
121x
112x
112x
1x
1x
27x
35x
4x
4x
31x
31x
31x
6x
6x
6x
6x
6x
6x
31x
2x
31x
30x
28x
27x
47x
47x
27x
374x
374x
374x
27x
216x
216x
216x
216x
216x
216x
432x
432x
216x
216x
213x
27x
179x
177x
174x
177x
27x
37x
37x
1x
173x
153x
137x
13x
13x
13x
173x
72x
70x
70x
27x
13x
13x
13x
13x
13x
13x
173x
191x
173x
374x
374x
374x
374x
374x
374x
2x
374x
374x
155x
219x
15x
204x
204x
374x
176x
1x
1x
374x
374x
27x
| import * as React from 'react';
import * as PropTypes from 'prop-types';
import ApolloClient, {
ObservableQuery,
ApolloError,
FetchPolicy,
ErrorPolicy,
ApolloQueryResult,
NetworkStatus,
} from 'apollo-client';
import { DocumentNode } from 'graphql';
import { ZenObservable } from 'zen-observable-ts';
import { OperationVariables, GraphqlQueryControls } from './types';
import { parser, DocumentType, IDocumentDefinition } from './parser';
const shallowEqual = require('fbjs/lib/shallowEqual');
const invariant = require('invariant');
// Improved FetchMoreOptions type, need to port them back to Apollo Client
export interface FetchMoreOptions<TData, TVariables> {
updateQuery: (
previousQueryResult: TData,
options: {
fetchMoreResult?: TData;
variables: TVariables;
},
) => TData;
}
// Improved FetchMoreQueryOptions type, need to port them back to Apollo Client
export interface FetchMoreQueryOptions<TVariables, K extends keyof TVariables> {
variables: Pick<TVariables, K>;
}
// XXX open types improvement PR to AC
// Improved ObservableQuery field types, need to port them back to Apollo Client
export type ObservableQueryFields<TData, TVariables> = Pick<
ObservableQuery<TData>,
'startPolling' | 'stopPolling' | 'subscribeToMore'
> & {
variables: TVariables;
refetch: (variables?: TVariables) => Promise<ApolloQueryResult<TData>>;
fetchMore: (<K extends keyof TVariables>(
fetchMoreOptions: FetchMoreQueryOptions<TVariables, K> & FetchMoreOptions<TData, TVariables>,
) => Promise<ApolloQueryResult<TData>>) &
(<TData2, TVariables2, K extends keyof TVariables2>(
fetchMoreOptions: { query: DocumentNode } & FetchMoreQueryOptions<TVariables2, K> &
FetchMoreOptions<TData2, TVariables2>,
) => Promise<ApolloQueryResult<TData2>>);
updateQuery: (
mapFn: (previousQueryResult: TData, options: { variables?: TVariables }) => TData,
) => void;
};
function compact(obj: any) {
return Object.keys(obj).reduce(
(acc, key) => {
if (obj[key] !== undefined) {
acc[key] = obj[key];
}
return acc;
},
{} as any,
);
}
function observableQueryFields<TData, TVariables>(
observable: ObservableQuery<TData>,
): ObservableQueryFields<TData, TVariables> {
const fields = {
variables: observable.variables,
refetch: observable.refetch.bind(observable),
fetchMore: observable.fetchMore.bind(observable),
updateQuery: observable.updateQuery.bind(observable),
startPolling: observable.startPolling.bind(observable),
stopPolling: observable.stopPolling.bind(observable),
subscribeToMore: observable.subscribeToMore.bind(observable),
};
// TODO: Need to cast this because we improved the type of `updateQuery` to be parametric
// on variables, while the type in Apollo client just has object.
// Consider removing this when that is properly typed
return fields as ObservableQueryFields<TData, TVariables>;
}
export interface QueryResult<TData = any, TVariables = OperationVariables>
extends ObservableQueryFields<TData, TVariables> {
client: ApolloClient<any>;
// we create an empty object to make checking for data
// easier for consumers (i.e. instead of data && data.user
// you can just check data.user) this also makes destructring
// easier (i.e. { data: { user } })
// however, this isn't realy possible with TypeScript that
// I'm aware of. So intead we enforce checking for data
// like so result.data!.user. This tells TS to use TData
// XXX is there a better way to do this?
data: TData | undefined;
error?: ApolloError;
loading: boolean;
networkStatus: NetworkStatus;
}
export interface QueryProps<TData = any, TVariables = OperationVariables> {
children: (result: QueryResult<TData, TVariables>) => React.ReactNode;
fetchPolicy?: FetchPolicy;
errorPolicy?: ErrorPolicy;
notifyOnNetworkStatusChange?: boolean;
pollInterval?: number;
query: DocumentNode;
variables?: TVariables;
ssr?: boolean;
displayName?: string;
skip?: boolean;
client?: ApolloClient<Object>;
context?: Record<string, any>;
}
export interface QueryContext {
client: ApolloClient<Object>;
operations?: Map<string, { query: DocumentNode; variables: any }>;
}
export default class Query<TData = any, TVariables = OperationVariables> extends React.Component<
QueryProps<TData, TVariables>
> {
static contextTypes = {
client: PropTypes.object.isRequired,
operations: PropTypes.object,
};
static propTypes = {
children: PropTypes.func.isRequired,
fetchPolicy: PropTypes.string,
notifyOnNetworkStatusChange: PropTypes.bool,
pollInterval: PropTypes.number,
query: PropTypes.object.isRequired,
variables: PropTypes.object,
ssr: PropTypes.bool,
};
context: QueryContext;
private client: ApolloClient<Object>;
// request / action storage. Note that we delete querySubscription if we
// unsubscribe but never delete queryObservable once it is created. We
// only delete queryObservable when we unmount the component.
private queryObservable: ObservableQuery<TData> | null;
private querySubscription: ZenObservable.Subscription;
private previousData: any = {};
private refetcherQueue: {
args: any;
resolve: (value?: any | PromiseLike<any>) => void;
reject: (reason?: any) => void;
};
private hasMounted: boolean;
private operation: IDocumentDefinition;
constructor(props: QueryProps<TData, TVariables>, context: QueryContext) {
super(props, context);
this.client = props.client || context.client;
invariant(
!!this.client,
`Could not find "client" in the context of Query or as passed props. Wrap the root component in an <ApolloProvider>`,
);
this.initializeQueryObservable(props);
}
// For server-side rendering (see getDataFromTree.ts)
fetchData(): Promise<ApolloQueryResult<any>> | boolean {
if (this.props.skip) return false;
// pull off react options
const { children, ssr, displayName, skip, client, ...opts } = this.props;
let { fetchPolicy } = opts;
if (ssr === false) return false;
if (fetchPolicy === 'network-only' || fetchPolicy === 'cache-and-network') {
fetchPolicy = 'cache-first'; // ignore force fetch in SSR;
}
const observable = this.client.watchQuery({
...opts,
fetchPolicy,
});
const result = this.queryObservable!.currentResult();
return result.loading ? observable.result() : false;
}
componentDidMount() {
this.hasMounted = true;
if (this.props.skip) return;
this.startQuerySubscription();
if (this.refetcherQueue) {
const { args, resolve, reject } = this.refetcherQueue;
this.queryObservable!.refetch(args)
.then(resolve)
.catch(reject);
}
}
componentWillReceiveProps(nextProps: QueryProps<TData, TVariables>, nextContext: QueryContext) {
// the next render wants to skip
if (nextProps.skip && !this.props.skip) {
this.removeQuerySubscription();
return;
}
const { client } = nextProps;
Iif (
shallowEqual(this.props, nextProps) &&
(this.client === client || this.client === nextContext.client)
) {
return;
}
if (this.client !== client && this.client !== nextContext.client) {
Iif (client) {
this.client = client;
} else {
this.client = nextContext.client;
}
this.removeQuerySubscription();
this.queryObservable = null;
this.previousData = {};
this.updateQuery(nextProps);
}
if (this.props.query !== nextProps.query) {
this.removeQuerySubscription();
}
this.updateQuery(nextProps);
if (nextProps.skip) return;
this.startQuerySubscription();
}
componentWillUnmount() {
this.removeQuerySubscription();
this.hasMounted = false;
}
render() {
const { children } = this.props;
const queryResult = this.getQueryResult();
return children(queryResult);
}
private extractOptsFromProps(props: QueryProps<TData, TVariables>) {
const {
variables,
pollInterval,
fetchPolicy,
errorPolicy,
notifyOnNetworkStatusChange,
query,
displayName = 'Query',
context = {},
} = props;
this.operation = parser(query);
invariant(
this.operation.type === DocumentType.Query,
`The <Query /> component requires a graphql query, but got a ${
this.operation.type === DocumentType.Mutation ? 'mutation' : 'subscription'
}.`,
);
return compact({
variables,
pollInterval,
query,
fetchPolicy,
errorPolicy,
notifyOnNetworkStatusChange,
metadata: { reactComponent: { displayName } },
context,
});
}
private initializeQueryObservable(props: QueryProps<TData, TVariables>) {
const opts = this.extractOptsFromProps(props);
// save for backwards compat of refetcherQueries without a recycler
if (this.context.operations) {
this.context.operations.set(this.operation.name, {
query: opts.query,
variables: opts.variables,
});
}
this.queryObservable = this.client.watchQuery(opts);
}
private updateQuery(props: QueryProps<TData, TVariables>) {
// if we skipped initially, we may not have yet created the observable
if (!this.queryObservable) this.initializeQueryObservable(props);
this.queryObservable!.setOptions(this.extractOptsFromProps(props))
// The error will be passed to the child container, so we don't
// need to log it here. We could conceivably log something if
// an option was set. OTOH we don't log errors w/ the original
// query. See https://github.com/apollostack/react-apollo/issues/404
.catch(() => null);
}
private startQuerySubscription = () => {
if (this.querySubscription) return;
this.querySubscription = this.queryObservable!.subscribe({
next: this.updateCurrentData,
error: error => {
this.resubscribeToQuery();
// Quick fix for https://github.com/apollostack/react-apollo/issues/378
Iif (!error.hasOwnProperty('graphQLErrors')) throw error;
this.updateCurrentData();
},
});
};
private removeQuerySubscription = () => {
if (this.querySubscription) {
this.querySubscription.unsubscribe();
delete this.querySubscription;
}
};
private resubscribeToQuery() {
this.removeQuerySubscription();
const lastError = this.queryObservable!.getLastError();
const lastResult = this.queryObservable!.getLastResult();
// If lastError is set, the observable will immediately
// send it, causing the stream to terminate on initialization.
// We clear everything here and restore it afterward to
// make sure the new subscription sticks.
this.queryObservable!.resetLastResults();
this.startQuerySubscription();
Object.assign(this.queryObservable!, { lastError, lastResult });
}
private updateCurrentData = () => {
// force a rerender that goes through shouldComponentUpdate
Eif (this.hasMounted) this.forceUpdate();
};
private getQueryResult = (): QueryResult<TData, TVariables> => {
let data = { data: Object.create(null) as TData } as any;
// attach bound methods
Object.assign(data, observableQueryFields(this.queryObservable!));
// fetch the current result (if any) from the store
const currentResult = this.queryObservable!.currentResult();
const { loading, networkStatus, errors } = currentResult;
let { error } = currentResult;
// until a set naming convention for networkError and graphQLErrors is decided upon, we map errors (graphQLErrors) to the error props
if (errors && errors.length > 0) {
error = new ApolloError({ graphQLErrors: errors });
}
Object.assign(data, { loading, networkStatus, error });
if (loading) {
Object.assign(data.data, this.previousData, currentResult.data);
} else if (error) {
Object.assign(data, {
data: (this.queryObservable!.getLastResult() || {}).data,
});
} else {
Object.assign(data.data, currentResult.data);
this.previousData = currentResult.data;
}
// handle race condition where refetch is called on child mount
if (!this.querySubscription) {
(data as GraphqlQueryControls).refetch = args => {
return new Promise((r, f) => {
this.refetcherQueue = { resolve: r, reject: f, args };
});
};
}
data.client = this.client;
return data;
};
}
|