-
-
Notifications
You must be signed in to change notification settings - Fork 459
/
query.ts
738 lines (675 loc) · 21.1 KB
/
query.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
import type { FormattedNode, CombinedError } from '@urql/core';
import { formatDocument } from '@urql/core';
import type {
FieldNode,
DocumentNode,
FragmentDefinitionNode,
} from '@0no-co/graphql.web';
import type { SelectionSet } from '../ast';
import {
getSelectionSet,
getName,
getFragmentTypeName,
getFieldAlias,
getFragments,
getMainOperation,
normalizeVariables,
getFieldArguments,
getDirectives,
} from '../ast';
import type {
Variables,
Data,
DataField,
Link,
OperationRequest,
Dependencies,
Resolver,
} from '../types';
import { joinKeys, keyOfField } from '../store/keys';
import type { Store } from '../store/store';
import * as InMemoryData from '../store/data';
import { warn, pushDebugNode, popDebugNode } from '../helpers/help';
import type { Context } from './shared';
import {
makeSelectionIterator,
ensureData,
makeContext,
updateContext,
getFieldError,
deferRef,
optionalRef,
} from './shared';
import {
isFieldAvailableOnType,
isFieldNullable,
isListNullable,
} from '../ast';
export interface QueryResult {
dependencies: Dependencies;
partial: boolean;
hasNext: boolean;
data: null | Data;
}
/** Reads a GraphQL query from the cache.
* @internal
*/
export const __initAnd_query = (
store: Store,
request: OperationRequest,
data?: Data | null | undefined,
error?: CombinedError | undefined,
key?: number
): QueryResult => {
InMemoryData.initDataState('read', store.data, key);
const result = _query(store, request, data, error);
InMemoryData.clearDataState();
return result;
};
/** Reads a GraphQL query from the cache.
* @internal
*/
export const _query = (
store: Store,
request: OperationRequest,
input?: Data | null | undefined,
error?: CombinedError | undefined
): QueryResult => {
const query = formatDocument(request.query);
const operation = getMainOperation(query);
const rootKey = store.rootFields[operation.operation];
const rootSelect = getSelectionSet(operation);
const ctx = makeContext(
store,
normalizeVariables(operation, request.variables),
getFragments(query),
rootKey,
rootKey,
error
);
if (process.env.NODE_ENV !== 'production') {
pushDebugNode(rootKey, operation);
}
// NOTE: This may reuse "previous result data" as indicated by the
// `originalData` argument in readRoot(). This behaviour isn't used
// for readSelection() however, which always produces results from
// scratch
const data =
rootKey !== ctx.store.rootFields['query']
? readRoot(ctx, rootKey, rootSelect, input || InMemoryData.makeData())
: readSelection(
ctx,
rootKey,
rootSelect,
input || InMemoryData.makeData()
);
if (process.env.NODE_ENV !== 'production') {
popDebugNode();
InMemoryData.getCurrentDependencies();
}
return {
dependencies: InMemoryData.currentDependencies!,
partial: ctx.partial || !data,
hasNext: ctx.hasNext,
data: data || null,
};
};
const readRoot = (
ctx: Context,
entityKey: string,
select: FormattedNode<SelectionSet>,
input: Data
): Data => {
const typename = ctx.store.rootNames[entityKey]
? entityKey
: input.__typename;
if (typeof typename !== 'string') {
return input;
}
const iterate = makeSelectionIterator(
entityKey,
entityKey,
false,
undefined,
select,
ctx
);
let node: FormattedNode<FieldNode> | void;
let hasChanged = InMemoryData.currentForeignData;
const output = InMemoryData.makeData(input);
while ((node = iterate())) {
const fieldAlias = getFieldAlias(node);
const fieldValue = input[fieldAlias];
// Add the current alias to the walked path before processing the field's value
ctx.__internal.path.push(fieldAlias);
// We temporarily store the data field in here, but undefined
// means that the value is missing from the cache
let dataFieldValue: void | DataField;
if (node.selectionSet && fieldValue !== null) {
dataFieldValue = readRootField(
ctx,
getSelectionSet(node),
ensureData(fieldValue)
);
} else {
dataFieldValue = fieldValue;
}
// Check for any referential changes in the field's value
hasChanged = hasChanged || dataFieldValue !== fieldValue;
if (dataFieldValue !== undefined) output[fieldAlias] = dataFieldValue!;
// After processing the field, remove the current alias from the path again
ctx.__internal.path.pop();
}
return hasChanged ? output : input;
};
const readRootField = (
ctx: Context,
select: FormattedNode<SelectionSet>,
originalData: Link<Data>
): Link<Data> => {
if (Array.isArray(originalData)) {
const newData = new Array(originalData.length);
let hasChanged = InMemoryData.currentForeignData;
for (let i = 0, l = originalData.length; i < l; i++) {
// Add the current index to the walked path before reading the field's value
ctx.__internal.path.push(i);
// Recursively read the root field's value
newData[i] = readRootField(ctx, select, originalData[i]);
hasChanged = hasChanged || newData[i] !== originalData[i];
// After processing the field, remove the current index from the path
ctx.__internal.path.pop();
}
return hasChanged ? newData : originalData;
} else if (originalData === null) {
return null;
}
// Write entity to key that falls back to the given parentFieldKey
const entityKey = ctx.store.keyOfEntity(originalData);
if (entityKey !== null) {
// We assume that since this is used for result data this can never be undefined,
// since the result data has already been written to the cache
return readSelection(ctx, entityKey, select, originalData) || null;
} else {
return readRoot(ctx, originalData.__typename, select, originalData);
}
};
export const _queryFragment = (
store: Store,
query: FormattedNode<DocumentNode>,
entity: Partial<Data> | string,
variables?: Variables,
fragmentName?: string
): Data | null => {
const fragments = getFragments(query);
let fragment: FormattedNode<FragmentDefinitionNode>;
if (fragmentName) {
fragment = fragments[fragmentName]!;
if (!fragment) {
warn(
'readFragment(...) was called with a fragment name that does not exist.\n' +
'You provided ' +
fragmentName +
' but could only find ' +
Object.keys(fragments).join(', ') +
'.',
6,
store.logger
);
return null;
}
} else {
const names = Object.keys(fragments);
fragment = fragments[names[0]]!;
if (!fragment) {
warn(
'readFragment(...) was called with an empty fragment.\n' +
'You have to call it with at least one fragment in your GraphQL document.',
6,
store.logger
);
return null;
}
}
const typename = getFragmentTypeName(fragment);
if (typeof entity !== 'string' && !entity.__typename)
entity.__typename = typename;
const entityKey = store.keyOfEntity(entity as Data);
if (!entityKey) {
warn(
"Can't generate a key for readFragment(...).\n" +
'You have to pass an `id` or `_id` field or create a custom `keys` config for `' +
typename +
'`.',
7,
store.logger
);
return null;
}
if (process.env.NODE_ENV !== 'production') {
pushDebugNode(typename, fragment);
}
const ctx = makeContext(
store,
variables || {},
fragments,
typename,
entityKey,
undefined
);
const result =
readSelection(
ctx,
entityKey,
getSelectionSet(fragment),
InMemoryData.makeData()
) || null;
if (process.env.NODE_ENV !== 'production') {
popDebugNode();
}
return result;
};
function getFieldResolver(
directives: ReturnType<typeof getDirectives>,
typename: string,
fieldName: string,
ctx: Context
): Resolver | void {
const resolvers = ctx.store.resolvers[typename];
const fieldResolver = resolvers && resolvers[fieldName];
let directiveResolver: Resolver | undefined;
for (const name in directives) {
const directiveNode = directives[name];
if (
directiveNode &&
name !== 'include' &&
name !== 'skip' &&
ctx.store.directives[name]
) {
directiveResolver = ctx.store.directives[name](
getFieldArguments(directiveNode, ctx.variables)
);
if (process.env.NODE_ENV === 'production') return directiveResolver;
break;
}
}
if (fieldResolver && directiveResolver) {
warn(
`A resolver and directive is being used at "${typename}.${fieldName}" simultaneously. Only the directive will apply.`,
28,
ctx.store.logger
);
}
return directiveResolver || fieldResolver;
}
const readSelection = (
ctx: Context,
key: string,
select: FormattedNode<SelectionSet>,
input: Data,
result?: Data
): Data | undefined => {
const { store } = ctx;
const isQuery = key === store.rootFields.query;
const entityKey = (result && store.keyOfEntity(result)) || key;
if (!isQuery && !!ctx.store.rootNames[entityKey]) {
warn(
'Invalid root traversal: A selection was being read on `' +
entityKey +
'` which is an uncached root type.\n' +
'The `' +
ctx.store.rootFields.mutation +
'` and `' +
ctx.store.rootFields.subscription +
'` types are special ' +
'Operation Root Types and cannot be read back from the cache.',
25,
store.logger
);
}
const typename = !isQuery
? InMemoryData.readRecord(entityKey, '__typename') ||
(result && result.__typename)
: key;
if (typeof typename !== 'string') {
return;
} else if (result && typename !== result.__typename) {
warn(
'Invalid resolver data: The resolver at `' +
entityKey +
'` returned an ' +
'invalid typename that could not be reconciled with the cache.',
8,
store.logger
);
return;
}
const iterate = makeSelectionIterator(
typename,
entityKey,
false,
undefined,
select,
ctx
);
let hasFields = false;
let hasNext = false;
let hasChanged = InMemoryData.currentForeignData;
let node: FormattedNode<FieldNode> | void;
const hasPartials = ctx.partial;
const output = InMemoryData.makeData(input);
while ((node = iterate()) !== undefined) {
// Derive the needed data from our node.
const fieldName = getName(node);
const fieldArgs = getFieldArguments(node, ctx.variables);
const fieldAlias = getFieldAlias(node);
const directives = getDirectives(node);
const resolver = getFieldResolver(directives, typename, fieldName, ctx);
const fieldKey = keyOfField(fieldName, fieldArgs);
const key = joinKeys(entityKey, fieldKey);
const fieldValue = InMemoryData.readRecord(entityKey, fieldKey);
const resultValue = result ? result[fieldName] : undefined;
if (process.env.NODE_ENV !== 'production' && store.schema && typename) {
isFieldAvailableOnType(
store.schema,
typename,
fieldName,
ctx.store.logger
);
}
// Add the current alias to the walked path before processing the field's value
ctx.__internal.path.push(fieldAlias);
// We temporarily store the data field in here, but undefined
// means that the value is missing from the cache
let dataFieldValue: void | DataField = undefined;
if (fieldName === '__typename') {
// We directly assign the typename as it's already available
dataFieldValue = typename;
} else if (resultValue !== undefined && node.selectionSet === undefined) {
// The field is a scalar and can be retrieved directly from the result
dataFieldValue = resultValue;
} else if (InMemoryData.currentOperation === 'read' && resolver) {
// We have a resolver for this field.
// Prepare the actual fieldValue, so that the resolver can use it,
// as to avoid the user having to do `cache.resolve(parent, info.fieldKey)`
// only to get a scalar value.
let parent = output;
if (node.selectionSet === undefined && fieldValue !== undefined) {
parent = {
...output,
[fieldAlias]: fieldValue,
[fieldName]: fieldValue,
};
}
// We have to update the information in context to reflect the info
// that the resolver will receive
updateContext(ctx, parent, typename, entityKey, fieldKey, fieldName);
dataFieldValue = resolver(
parent,
fieldArgs || ({} as Variables),
store,
ctx
);
if (node.selectionSet) {
// When it has a selection set we are resolving an entity with a
// subselection. This can either be a list or an object.
dataFieldValue = resolveResolverResult(
ctx,
typename,
fieldName,
key,
getSelectionSet(node),
(output[fieldAlias] !== undefined
? output[fieldAlias]
: input[fieldAlias]) as Data,
dataFieldValue,
InMemoryData.ownsData(input)
);
}
if (
store.schema &&
dataFieldValue === null &&
!isFieldNullable(store.schema, typename, fieldName, ctx.store.logger)
) {
// Special case for when null is not a valid value for the
// current field
return undefined;
}
} else if (!node.selectionSet) {
// The field is a scalar but isn't on the result, so it's retrieved from the cache
dataFieldValue = fieldValue;
} else if (resultValue !== undefined) {
// We start walking the nested resolver result here
dataFieldValue = resolveResolverResult(
ctx,
typename,
fieldName,
key,
getSelectionSet(node),
(output[fieldAlias] !== undefined
? output[fieldAlias]
: input[fieldAlias]) as Data,
resultValue,
InMemoryData.ownsData(input)
);
} else {
// Otherwise we attempt to get the missing field from the cache
const link = InMemoryData.readLink(entityKey, fieldKey);
if (link !== undefined) {
dataFieldValue = resolveLink(
ctx,
link,
typename,
fieldName,
getSelectionSet(node),
(output[fieldAlias] !== undefined
? output[fieldAlias]
: input[fieldAlias]) as Data,
InMemoryData.ownsData(input)
);
} else if (typeof fieldValue === 'object' && fieldValue !== null) {
// The entity on the field was invalid but can still be recovered
dataFieldValue = fieldValue;
}
}
// Now that dataFieldValue has been retrieved it'll be set on data
// If it's uncached (undefined) but nullable we can continue assembling
// a partial query result
if (
!deferRef &&
dataFieldValue === undefined &&
(directives.optional ||
(optionalRef && !directives.required) ||
!!getFieldError(ctx) ||
(store.schema &&
isFieldNullable(store.schema, typename, fieldName, ctx.store.logger)))
) {
// The field is uncached or has errored, so it'll be set to null and skipped
ctx.partial = true;
dataFieldValue = null;
} else if (
dataFieldValue === null &&
(directives.required || optionalRef === false)
) {
if (
ctx.store.logger &&
process.env.NODE_ENV !== 'production' &&
InMemoryData.currentOperation === 'read'
) {
ctx.store.logger(
'debug',
`Got value "null" for required field "${fieldName}"${
fieldArgs ? ` with args ${JSON.stringify(fieldArgs)}` : ''
} on entity "${entityKey}"`
);
}
dataFieldValue = undefined;
} else {
hasFields = hasFields || fieldName !== '__typename';
}
// After processing the field, remove the current alias from the path again
ctx.__internal.path.pop();
// Check for any referential changes in the field's value
hasChanged = hasChanged || dataFieldValue !== input[fieldAlias];
if (dataFieldValue !== undefined) {
output[fieldAlias] = dataFieldValue;
} else if (deferRef) {
hasNext = true;
} else {
if (
ctx.store.logger &&
process.env.NODE_ENV !== 'production' &&
InMemoryData.currentOperation === 'read'
) {
ctx.store.logger(
'debug',
`No value for field "${fieldName}"${
fieldArgs ? ` with args ${JSON.stringify(fieldArgs)}` : ''
} on entity "${entityKey}"`
);
}
// If the field isn't deferred or partial then we have to abort and also reset
// the partial field
ctx.partial = hasPartials;
return undefined;
}
}
ctx.partial = ctx.partial || hasPartials;
ctx.hasNext = ctx.hasNext || hasNext;
return isQuery && ctx.partial && !hasFields
? undefined
: hasChanged
? output
: input;
};
const resolveResolverResult = (
ctx: Context,
typename: string,
fieldName: string,
key: string,
select: FormattedNode<SelectionSet>,
prevData: void | null | Data | Data[],
result: void | DataField,
isOwnedData: boolean
): DataField | void => {
if (Array.isArray(result)) {
const { store } = ctx;
// Check whether values of the list may be null; for resolvers we assume
// that they can be, since it's user-provided data
const _isListNullable = store.schema
? isListNullable(store.schema, typename, fieldName, ctx.store.logger)
: false;
const hasPartials = ctx.partial;
const data = InMemoryData.makeData(prevData, true);
let hasChanged =
InMemoryData.currentForeignData ||
!Array.isArray(prevData) ||
result.length !== prevData.length;
for (let i = 0, l = result.length; i < l; i++) {
// Add the current index to the walked path before reading the field's value
ctx.__internal.path.push(i);
// Recursively read resolver result
const childResult = resolveResolverResult(
ctx,
typename,
fieldName,
joinKeys(key, `${i}`),
select,
prevData != null ? prevData[i] : undefined,
result[i],
isOwnedData
);
// After processing the field, remove the current index from the path
ctx.__internal.path.pop();
// Check the result for cache-missed values
if (childResult === undefined && !_isListNullable) {
ctx.partial = hasPartials;
return undefined;
} else {
ctx.partial =
ctx.partial || (childResult === undefined && _isListNullable);
data[i] = childResult != null ? childResult : null;
hasChanged = hasChanged || data[i] !== prevData![i];
}
}
return hasChanged ? data : prevData;
} else if (result === null || result === undefined) {
return result;
} else if (isOwnedData && prevData === null) {
return null;
} else if (isDataOrKey(result)) {
const data = (prevData || InMemoryData.makeData(prevData)) as Data;
return typeof result === 'string'
? readSelection(ctx, result, select, data)
: readSelection(ctx, key, select, data, result);
} else {
warn(
'Invalid resolver value: The field at `' +
key +
'` is a scalar (number, boolean, etc)' +
', but the GraphQL query expects a selection set for this field.',
9,
ctx.store.logger
);
return undefined;
}
};
const resolveLink = (
ctx: Context,
link: Link | Link[],
typename: string,
fieldName: string,
select: FormattedNode<SelectionSet>,
prevData: void | null | Data | Data[],
isOwnedData: boolean
): DataField | undefined => {
if (Array.isArray(link)) {
const { store } = ctx;
const _isListNullable = store.schema
? isListNullable(store.schema, typename, fieldName, ctx.store.logger)
: false;
const newLink = InMemoryData.makeData(prevData, true);
const hasPartials = ctx.partial;
let hasChanged =
InMemoryData.currentForeignData ||
!Array.isArray(prevData) ||
link.length !== prevData.length;
for (let i = 0, l = link.length; i < l; i++) {
// Add the current index to the walked path before reading the field's value
ctx.__internal.path.push(i);
// Recursively read the link
const childLink = resolveLink(
ctx,
link[i],
typename,
fieldName,
select,
prevData != null ? prevData[i] : undefined,
isOwnedData
);
// After processing the field, remove the current index from the path
ctx.__internal.path.pop();
// Check the result for cache-missed values
if (childLink === undefined && !_isListNullable) {
ctx.partial = hasPartials;
return undefined;
} else {
ctx.partial =
ctx.partial || (childLink === undefined && _isListNullable);
newLink[i] = childLink || null;
hasChanged = hasChanged || newLink[i] !== prevData![i];
}
}
return hasChanged ? newLink : (prevData as Data[]);
} else if (link === null || (prevData === null && isOwnedData)) {
return null;
}
return readSelection(
ctx,
link,
select,
(prevData || InMemoryData.makeData(prevData)) as Data
);
};
const isDataOrKey = (x: any): x is string | Data =>
typeof x === 'string' ||
(typeof x === 'object' && typeof (x as any).__typename === 'string');