-
-
Notifications
You must be signed in to change notification settings - Fork 461
/
Copy pathclient.ts
executable file
·442 lines (382 loc) · 13.4 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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/* eslint-disable @typescript-eslint/no-use-before-define */
import {
filter,
make,
makeSubject,
onEnd,
onPush,
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,
getOperationType,
} 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;
}
export interface Client {
new (options: ClientOptions): Client;
operations$: Source<Operation>;
/** Start an operation from an exchange */
reexecuteOperation: (operation: Operation) => void;
/** Event target for monitoring, e.g. for @urql/devtools */
subscribeToDebugTarget?: (onEvent: (e: DebugEvent) => void) => Subscription;
// These are variables derived from ClientOptions
url: string;
fetch?: typeof fetch;
fetchOptions?: RequestInit | (() => RequestInit);
suspense: boolean;
requestPolicy: RequestPolicy;
preferGetMethod: boolean;
maskTypename: boolean;
createOperationContext(
opts?: Partial<OperationContext> | undefined
): OperationContext;
createRequestOperation<Data = any, Variables = object>(
kind: OperationType,
request: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext> | undefined
): Operation<Data, Variables>;
/** 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>>;
query<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): PromisifiedSource<OperationResult<Data, Variables>>;
readQuery<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): OperationResult<Data, Variables> | null;
executeQuery<Data = any, Variables = object>(
query: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext> | undefined
): Source<OperationResult<Data, Variables>>;
subscription<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): Source<OperationResult<Data, Variables>>;
executeSubscription<Data = any, Variables = object>(
query: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext> | undefined
): Source<OperationResult<Data, Variables>>;
mutation<Data = any, Variables extends object = {}>(
query: DocumentNode | TypedDocumentNode<Data, Variables> | string,
variables?: Variables,
context?: Partial<OperationContext>
): PromisifiedSource<OperationResult<Data, Variables>>;
executeMutation<Data = any, Variables = object>(
query: GraphQLRequest<Data, Variables>,
opts?: Partial<OperationContext> | undefined
): Source<OperationResult<Data, Variables>>;
}
export const Client: new (opts: ClientOptions) => Client = function Client(
this: Client | {},
opts: ClientOptions
) {
if (process.env.NODE_ENV !== 'production' && !opts.url) {
throw new Error('You are creating an urql-client without a url.');
}
const replays = new Map<number, OperationResult>();
const active: Map<number, Source<OperationResult>> = new Map();
const queue: Operation[] = [];
// 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>();
// We define a queued dispatcher on the subject, which empties the queue when it's
// activated to allow `reexecuteOperation` to be trampoline-scheduled
let isOperationBatchActive = false;
function dispatchOperation(operation?: Operation | void) {
isOperationBatchActive = true;
if (operation) nextOperation(operation);
while ((operation = queue.shift())) nextOperation(operation);
isOperationBatchActive = false;
}
/** Defines how result streams are created */
const makeResultSource = (operation: Operation) => {
let result$ = pipe(
results$,
filter((res: OperationResult) => {
return (
res.operation.kind === operation.kind &&
res.operation.key === operation.key &&
(!res.operation.context._instance ||
res.operation.context._instance === operation.context._instance)
);
})
);
// Mask typename properties if the option for it is turned on
if (client.maskTypename) {
result$ = pipe(
result$,
map(res => ({ ...res, data: maskTypename(res.data) }))
);
}
// A mutation is always limited to just a single result and is never shared
if (operation.kind === 'mutation') {
return pipe(
result$,
onStart(() => dispatchOperation(operation)),
take(1)
);
}
const source = pipe(
result$,
// End the results stream when an active teardown event is sent
takeUntil(
pipe(
operations$,
filter(op => op.kind === 'teardown' && op.key === operation.key)
)
),
switchMap(result => {
if (operation.kind !== 'query' || result.stale) {
return fromValue(result);
}
return merge([
fromValue(result),
// Mark a result as stale when a new operation is sent for it
pipe(
operations$,
filter(
op =>
op.kind === 'query' &&
op.key === operation.key &&
op.context.requestPolicy !== 'cache-only'
),
take(1),
map(() => ({ ...result, stale: true }))
),
]);
}),
onPush(result => {
replays.set(operation.key, result);
}),
onEnd(() => {
// Delete the active operation handle
replays.delete(operation.key);
active.delete(operation.key);
// Delete all queued up operations of the same key on end
for (let i = queue.length - 1; i >= 0; i--)
if (queue[i].key === operation.key) queue.splice(i, 1);
// Dispatch a teardown signal for the stopped operation
dispatchOperation(
makeOperation('teardown', operation, operation.context)
);
}),
share
);
return source;
};
const instance: Client =
this instanceof Client ? this : Object.create(Client.prototype);
const client: Client = Object.assign(instance, {
url: opts.url,
fetchOptions: opts.fetchOptions,
fetch: opts.fetch,
suspense: !!opts.suspense,
requestPolicy: opts.requestPolicy || 'cache-first',
preferGetMethod: !!opts.preferGetMethod,
maskTypename: !!opts.maskTypename,
operations$,
reexecuteOperation(operation: Operation) {
// Reexecute operation only if any subscribers are still subscribed to the
// operation's exchange results
if (operation.kind === 'mutation' || active.has(operation.key)) {
queue.push(operation);
if (!isOperationBatchActive) {
Promise.resolve().then(dispatchOperation);
}
}
},
createOperationContext(opts) {
if (!opts) opts = {};
return {
_instance: undefined,
url: client.url,
fetchOptions: client.fetchOptions,
fetch: client.fetch,
preferGetMethod: client.preferGetMethod,
...opts,
suspense: opts.suspense || (opts.suspense !== false && client.suspense),
requestPolicy: opts.requestPolicy || client.requestPolicy,
};
},
createRequestOperation(kind, request, opts) {
const requestOperationType = getOperationType(request.query);
if (
process.env.NODE_ENV !== 'production' &&
kind !== 'teardown' &&
requestOperationType !== kind
) {
throw new Error(
`Expected operation of type "${kind}" but found "${requestOperationType}"`
);
}
const context = client.createOperationContext(opts);
if (kind === 'mutation') (context as any)._instance = [];
return makeOperation(kind, request, context);
},
executeRequestOperation(operation) {
if (operation.kind === 'mutation') {
return makeResultSource(operation);
}
return make(observer => {
let source = active.get(operation.key);
if (!source) {
active.set(operation.key, (source = makeResultSource(operation)));
}
const isNetworkOperation =
operation.context.requestPolicy === 'cache-and-network' ||
operation.context.requestPolicy === 'network-only';
return pipe(
source,
onStart(() => {
const prevReplay = replays.get(operation.key);
if (operation.kind === 'subscription') {
return dispatchOperation(operation);
} else if (isNetworkOperation) {
dispatchOperation(operation);
}
if (
prevReplay != null &&
prevReplay === replays.get(operation.key)
) {
observer.next(
isNetworkOperation ? { ...prevReplay, stale: true } : prevReplay
);
} else if (!isNetworkOperation) {
dispatchOperation(operation);
}
}),
onEnd(observer.complete),
subscribe(observer.next)
).unsubscribe;
});
},
executeQuery(query, opts) {
const operation = client.createRequestOperation('query', query, opts);
return client.executeRequestOperation(operation);
},
executeSubscription(query, opts) {
const operation = client.createRequestOperation(
'subscription',
query,
opts
);
return client.executeRequestOperation(operation);
},
executeMutation(query, opts) {
const operation = client.createRequestOperation('mutation', query, opts);
return client.executeRequestOperation(operation);
},
query(query, variables, context) {
if (!context || typeof context.suspense !== 'boolean') {
context = { ...context, suspense: false };
}
return withPromise(
client.executeQuery(createRequest(query, variables), context)
);
},
readQuery(query, variables, context) {
let result: OperationResult | null = null;
pipe(
client.query(query, variables, context),
subscribe(res => {
result = res;
})
).unsubscribe();
return result;
},
subscription(query, variables, context) {
return client.executeSubscription(
createRequest(query, variables),
context
);
},
mutation(query, variables, context) {
return withPromise(
client.executeMutation(createRequest(query, variables), context)
);
},
} as Client);
let dispatchDebug: ExchangeInput['dispatchDebug'] = noop;
if (process.env.NODE_ENV !== 'production') {
const { next, source } = makeSubject<DebugEvent>();
client.subscribeToDebugTarget = (onEvent: (e: DebugEvent) => void) =>
pipe(source, subscribe(onEvent));
dispatchDebug = next as ExchangeInput['dispatchDebug'];
}
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
const results$ = share(
composedExchange({
client,
dispatchDebug,
forward: fallbackExchange({ dispatchDebug }),
})(operations$)
);
// Prevent the `results$` exchange pipeline from being closed by active
// cancellations cascading up from components
pipe(results$, publish);
return client;
} as any;
export const createClient = (Client as any) as (opts: ClientOptions) => Client;