-
-
Notifications
You must be signed in to change notification settings - Fork 454
/
client.ts
executable file
·377 lines (332 loc) · 11.7 KB
/
client.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
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
/* eslint-disable @typescript-eslint/no-use-before-define */
import {
filter,
makeSubject,
onEnd,
onStart,
pipe,
share,
Source,
take,
takeUntil,
publish,
subscribe,
switchMap,
fromValue,
merge,
map,
Subscription,
} from 'wonka';
import { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { DocumentNode } from 'graphql';
import { composeExchanges, defaultExchanges } from './exchanges';
import { fallbackExchange } from './exchanges/fallback';
import {
Exchange,
ExchangeInput,
GraphQLRequest,
Operation,
OperationContext,
OperationResult,
OperationType,
RequestPolicy,
PromisifiedSource,
DebugEvent,
} from './types';
import {
createRequest,
withPromise,
maskTypename,
noop,
makeOperation,
} from './utils';
/** Options for configuring the URQL [client]{@link Client}. */
export interface ClientOptions {
/** Target endpoint URL such as `https://my-target:8080/graphql`. */
url: string;
/** Any additional options to pass to fetch. */
fetchOptions?: RequestInit | (() => RequestInit);
/** An alternative fetch implementation. */
fetch?: typeof fetch;
/** An ordered array of Exchanges. */
exchanges?: Exchange[];
/** Activates support for Suspense. */
suspense?: boolean;
/** The default request policy for requests. */
requestPolicy?: RequestPolicy;
/** Use HTTP GET for queries. */
preferGetMethod?: boolean;
/** Mask __typename from results. */
maskTypename?: boolean;
}
interface ActiveOperations {
[operationKey: string]: number;
}
export const createClient = (opts: ClientOptions) => new Client(opts);
/** The URQL application-wide client library. Each execute method starts a GraphQL request and returns a stream of results. */
export class Client {
/** Start an operation from an exchange */
reexecuteOperation: (operation: Operation) => void;
// Event target for monitoring
subscribeToDebugTarget?: (onEvent: (e: DebugEvent) => void) => Subscription;
// These are variables derived from ClientOptions
url: string;
fetch?: typeof fetch;
fetchOptions?: RequestInit | (() => RequestInit);
suspense: boolean;
preferGetMethod: boolean;
requestPolicy: RequestPolicy;
maskTypename: boolean;
// These are internals to be used to keep track of operations
dispatchOperation: (operation?: Operation | void) => void;
operations$: Source<Operation>;
results$: Source<OperationResult>;
activeOperations = Object.create(null) as ActiveOperations;
queue: Operation[] = [];
constructor(opts: ClientOptions) {
if (process.env.NODE_ENV !== 'production' && !opts.url) {
throw new Error('You are creating an urql-client without a url.');
}
let dispatchDebug: ExchangeInput['dispatchDebug'] = noop;
if (process.env.NODE_ENV !== 'production') {
const { next, source } = makeSubject<DebugEvent>();
this.subscribeToDebugTarget = (onEvent: (e: DebugEvent) => void) =>
pipe(source, subscribe(onEvent));
dispatchDebug = next as ExchangeInput['dispatchDebug'];
}
this.url = opts.url;
this.fetchOptions = opts.fetchOptions;
this.fetch = opts.fetch;
this.suspense = !!opts.suspense;
this.requestPolicy = opts.requestPolicy || 'cache-first';
this.preferGetMethod = !!opts.preferGetMethod;
this.maskTypename = !!opts.maskTypename;
// This subject forms the input of operations; executeOperation may be
// called to dispatch a new operation on the subject
const {
source: operations$,
next: nextOperation,
} = makeSubject<Operation>();
this.operations$ = operations$;
let isOperationBatchActive = false;
this.dispatchOperation = (operation?: Operation | void) => {
isOperationBatchActive = true;
if (operation) nextOperation(operation);
while ((operation = this.queue.shift())) nextOperation(operation);
isOperationBatchActive = false;
};
this.reexecuteOperation = (operation: Operation) => {
// Reexecute operation only if any subscribers are still subscribed to the
// operation's exchange results
if (
operation.kind === 'mutation' ||
(this.activeOperations[operation.key] || 0) > 0
) {
this.queue.push(operation);
if (!isOperationBatchActive) {
Promise.resolve().then(this.dispatchOperation);
}
}
};
const exchanges =
opts.exchanges !== undefined ? opts.exchanges : defaultExchanges;
// All exchange are composed into a single one and are called using the constructed client
// and the fallback exchange stream
const composedExchange = composeExchanges(exchanges);
// All exchanges receive inputs using which they can forward operations to the next exchange
// and receive a stream of results in return, access the client, or dispatch debugging events
// All operations then run through the Exchange IOs in a pipeline-like fashion
this.results$ = share(
composedExchange({
client: this,
dispatchDebug,
forward: fallbackExchange({ dispatchDebug }),
})(this.operations$)
);
// Prevent the `results$` exchange pipeline from being closed by active
// cancellations cascading up from components
pipe(this.results$, publish);
}
createOperationContext = (
opts?: Partial<OperationContext>
): OperationContext => {
if (!opts) opts = {};
return {
url: this.url,
fetchOptions: this.fetchOptions,
fetch: this.fetch,
preferGetMethod: this.preferGetMethod,
...opts,
suspense: opts.suspense || (opts.suspense !== false && this.suspense),
requestPolicy: opts.requestPolicy || this.requestPolicy,
};
};
createRequestOperation = <Data = any, Variables = object>(
kind: OperationType,
request: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext>
): Operation<Data, Variables> =>
makeOperation<Data, Variables>(
kind,
request,
this.createOperationContext(opts)
);
/** Counts up the active operation key and dispatches the operation */
private onOperationStart(operation: Operation) {
const { key } = operation;
this.activeOperations[key] = (this.activeOperations[key] || 0) + 1;
this.dispatchOperation(operation);
}
/** Deletes an active operation's result observable and sends a teardown signal through the exchange pipeline */
private onOperationEnd(operation: Operation) {
const { key } = operation;
const prevActive = this.activeOperations[key] || 0;
const newActive = (this.activeOperations[key] =
prevActive <= 0 ? 0 : prevActive - 1);
// Check whether this operation has now become inactive
if (newActive <= 0) {
// Delete all related queued up operations for the inactive one
for (let i = this.queue.length - 1; i >= 0; i--)
if (this.queue[i].key === operation.key) this.queue.splice(i, 1);
// Issue the cancellation teardown operation
this.dispatchOperation(
makeOperation('teardown', operation, operation.context)
);
}
}
/** Executes an Operation by sending it through the exchange pipeline It returns an observable that emits all related exchange results and keeps track of this observable's subscribers. A teardown signal will be emitted when no subscribers are listening anymore. */
executeRequestOperation<Data = any, Variables = object>(
operation: Operation<Data, Variables>
): Source<OperationResult<Data, Variables>> {
let operationResults$ = pipe(
this.results$,
filter((res: OperationResult) => res.operation.key === operation.key)
) as Source<OperationResult<Data, Variables>>;
if (this.maskTypename) {
operationResults$ = pipe(
operationResults$,
map(res => {
res.data = maskTypename(res.data);
return res;
})
);
}
if (operation.kind === 'mutation') {
// A mutation is always limited to just a single result and is never shared
return pipe(
operationResults$,
onStart<OperationResult>(() => this.dispatchOperation(operation)),
take(1)
);
}
const teardown$ = pipe(
this.operations$,
filter(
(op: Operation) => op.kind === 'teardown' && op.key === operation.key
)
);
const refetch$ = pipe(
this.operations$,
filter(
(op: Operation) =>
op.kind === operation.kind &&
op.key === operation.key &&
op.context.requestPolicy !== 'cache-only'
)
);
const result$ = pipe(
operationResults$,
takeUntil(teardown$),
switchMap(result => {
if (result.stale) return fromValue(result);
return merge([
fromValue(result),
pipe(
refetch$,
take(1),
map(() => ({ ...result, stale: true }))
),
]);
}),
onStart<OperationResult>(() => {
this.onOperationStart(operation);
}),
onEnd<OperationResult>(() => {
this.onOperationEnd(operation);
})
);
return result$;
}
query<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): PromisifiedSource<OperationResult<Data, Variables>> {
if (!context || typeof context.suspense !== 'boolean') {
context = { ...context, suspense: false };
}
return withPromise<OperationResult<Data, Variables>>(
this.executeQuery<Data, Variables>(
createRequest(query, variables),
context
)
);
}
readQuery<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): OperationResult<Data, Variables> | null {
let result: OperationResult<Data, Variables> | null = null;
pipe(
this.executeQuery(createRequest(query, variables), context),
subscribe(res => {
result = res;
})
).unsubscribe();
return result;
}
executeQuery = <Data = any, Variables = object>(
query: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext>
): Source<OperationResult<Data, Variables>> => {
const operation = this.createRequestOperation('query', query, opts);
return this.executeRequestOperation<Data, Variables>(operation);
};
subscription<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): Source<OperationResult<Data, Variables>> {
return this.executeSubscription<Data, Variables>(
createRequest(query, variables),
context
);
}
executeSubscription = <Data = any, Variables = object>(
query: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext>
): Source<OperationResult<Data, Variables>> => {
const operation = this.createRequestOperation('subscription', query, opts);
return this.executeRequestOperation<Data, Variables>(operation);
};
mutation<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): PromisifiedSource<OperationResult<Data, Variables>> {
return withPromise<OperationResult<Data, Variables>>(
this.executeMutation<Data, Variables>(
createRequest(query, variables),
context
)
);
}
executeMutation = <Data = any, Variables = object>(
query: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext>
): Source<OperationResult<Data, Variables>> => {
const operation = this.createRequestOperation('mutation', query, opts);
return this.executeRequestOperation<Data, Variables>(operation);
};
}