@isograph/react 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/FragmentReference.d.ts +15 -0
- package/dist/core/FragmentReference.js +17 -0
- package/dist/core/IsographEnvironment.d.ts +71 -0
- package/dist/core/IsographEnvironment.js +72 -0
- package/dist/core/PromiseWrapper.d.ts +27 -0
- package/dist/core/PromiseWrapper.js +58 -0
- package/dist/core/areEqualWithDeepComparison.d.ts +3 -0
- package/dist/core/areEqualWithDeepComparison.js +61 -0
- package/dist/core/cache.d.ts +28 -0
- package/dist/core/cache.js +452 -0
- package/dist/core/componentCache.d.ts +5 -0
- package/dist/core/componentCache.js +38 -0
- package/dist/core/entrypoint.d.ts +50 -0
- package/dist/core/entrypoint.js +8 -0
- package/dist/core/garbageCollection.d.ts +11 -0
- package/dist/core/garbageCollection.js +74 -0
- package/dist/core/makeNetworkRequest.d.ts +6 -0
- package/dist/core/makeNetworkRequest.js +62 -0
- package/dist/core/read.d.ts +12 -0
- package/dist/core/read.js +415 -0
- package/dist/core/reader.d.ts +63 -0
- package/dist/core/reader.js +2 -0
- package/dist/core/util.d.ts +17 -0
- package/dist/core/util.js +2 -0
- package/dist/index.d.ts +21 -120
- package/dist/index.js +49 -306
- package/dist/loadable-hooks/useClientSideDefer.d.ts +4 -0
- package/dist/loadable-hooks/useClientSideDefer.js +15 -0
- package/dist/loadable-hooks/useImperativeExposedMutationField.d.ts +5 -0
- package/dist/loadable-hooks/useImperativeExposedMutationField.js +15 -0
- package/dist/loadable-hooks/useImperativeLoadableField.d.ts +9 -0
- package/dist/loadable-hooks/useImperativeLoadableField.js +15 -0
- package/dist/loadable-hooks/useSkipLimitPagination.d.ts +33 -0
- package/dist/loadable-hooks/useSkipLimitPagination.js +118 -0
- package/dist/react/FragmentReader.d.ts +13 -0
- package/dist/{EntrypointReader.js → react/FragmentReader.js} +5 -5
- package/dist/react/IsographEnvironmentProvider.d.ts +10 -0
- package/dist/{IsographEnvironment.js → react/IsographEnvironmentProvider.js} +2 -20
- package/dist/react/useImperativeReference.d.ts +7 -0
- package/dist/react/useImperativeReference.js +36 -0
- package/dist/react/useLazyReference.d.ts +5 -0
- package/dist/react/useLazyReference.js +14 -0
- package/dist/react/useReadAndSubscribe.d.ts +11 -0
- package/dist/react/useReadAndSubscribe.js +41 -0
- package/dist/react/useRerenderOnChange.d.ts +3 -0
- package/dist/react/useRerenderOnChange.js +23 -0
- package/dist/react/useResult.d.ts +5 -0
- package/dist/react/useResult.js +36 -0
- package/docs/how-useLazyReference-works.md +117 -0
- package/package.json +11 -6
- package/src/core/FragmentReference.ts +37 -0
- package/src/core/IsographEnvironment.ts +183 -0
- package/src/core/PromiseWrapper.ts +86 -0
- package/src/core/areEqualWithDeepComparison.ts +78 -0
- package/src/core/cache.ts +721 -0
- package/src/core/componentCache.ts +61 -0
- package/src/core/entrypoint.ts +99 -0
- package/src/core/garbageCollection.ts +122 -0
- package/src/core/makeNetworkRequest.ts +99 -0
- package/src/core/read.ts +615 -0
- package/src/core/reader.ts +133 -0
- package/src/core/util.ts +23 -0
- package/src/index.ts +86 -0
- package/src/loadable-hooks/useClientSideDefer.ts +28 -0
- package/src/loadable-hooks/useImperativeExposedMutationField.ts +17 -0
- package/src/loadable-hooks/useImperativeLoadableField.ts +26 -0
- package/src/loadable-hooks/useSkipLimitPagination.ts +211 -0
- package/src/react/FragmentReader.tsx +34 -0
- package/src/react/IsographEnvironmentProvider.tsx +33 -0
- package/src/react/useImperativeReference.ts +57 -0
- package/src/react/useLazyReference.ts +22 -0
- package/src/react/useReadAndSubscribe.ts +66 -0
- package/src/react/useRerenderOnChange.ts +33 -0
- package/src/react/useResult.ts +65 -0
- package/src/tests/__isograph/Query/meName/entrypoint.ts +47 -0
- package/src/tests/__isograph/Query/meName/output_type.ts +3 -0
- package/src/tests/__isograph/Query/meName/param_type.ts +6 -0
- package/src/tests/__isograph/Query/meName/resolver_reader.ts +32 -0
- package/src/tests/__isograph/Query/meNameSuccessor/entrypoint.ts +83 -0
- package/src/tests/__isograph/Query/meNameSuccessor/output_type.ts +3 -0
- package/src/tests/__isograph/Query/meNameSuccessor/param_type.ts +11 -0
- package/src/tests/__isograph/Query/meNameSuccessor/resolver_reader.ts +54 -0
- package/src/tests/__isograph/Query/nodeField/entrypoint.ts +46 -0
- package/src/tests/__isograph/Query/nodeField/output_type.ts +3 -0
- package/src/tests/__isograph/Query/nodeField/param_type.ts +6 -0
- package/src/tests/__isograph/Query/nodeField/resolver_reader.ts +37 -0
- package/src/tests/__isograph/iso.ts +88 -0
- package/src/tests/garbageCollection.test.ts +136 -0
- package/src/tests/isograph.config.json +7 -0
- package/src/tests/meNameSuccessor.ts +20 -0
- package/src/tests/nodeQuery.ts +17 -0
- package/src/tests/schema.graphql +16 -0
- package/src/tests/tsconfig.json +21 -0
- package/tsconfig.json +6 -0
- package/tsconfig.pkg.json +2 -1
- package/dist/EntrypointReader.d.ts +0 -6
- package/dist/IsographEnvironment.d.ts +0 -56
- package/dist/PromiseWrapper.d.ts +0 -13
- package/dist/PromiseWrapper.js +0 -22
- package/dist/cache.d.ts +0 -26
- package/dist/cache.js +0 -274
- package/dist/componentCache.d.ts +0 -6
- package/dist/componentCache.js +0 -31
- package/dist/useImperativeReference.d.ts +0 -8
- package/dist/useImperativeReference.js +0 -28
- package/src/EntrypointReader.tsx +0 -20
- package/src/IsographEnvironment.tsx +0 -120
- package/src/PromiseWrapper.ts +0 -29
- package/src/cache.tsx +0 -484
- package/src/componentCache.ts +0 -41
- package/src/index.tsx +0 -617
- package/src/useImperativeReference.ts +0 -58
@@ -0,0 +1,721 @@
|
|
1
|
+
import {
|
2
|
+
Factory,
|
3
|
+
ItemCleanupPair,
|
4
|
+
ParentCache,
|
5
|
+
} from '@isograph/react-disposable-state';
|
6
|
+
import {
|
7
|
+
DataId,
|
8
|
+
ROOT_ID,
|
9
|
+
StoreRecord,
|
10
|
+
Link,
|
11
|
+
type IsographEnvironment,
|
12
|
+
DataTypeValue,
|
13
|
+
getLink,
|
14
|
+
FragmentSubscription,
|
15
|
+
} from './IsographEnvironment';
|
16
|
+
import {
|
17
|
+
IsographEntrypoint,
|
18
|
+
NormalizationAst,
|
19
|
+
NormalizationInlineFragment,
|
20
|
+
NormalizationLinkedField,
|
21
|
+
NormalizationScalarField,
|
22
|
+
RefetchQueryNormalizationArtifactWrapper,
|
23
|
+
} from '../core/entrypoint';
|
24
|
+
import { ReaderLinkedField, ReaderScalarField } from './reader';
|
25
|
+
import { Argument, ArgumentValue } from './util';
|
26
|
+
import { WithEncounteredRecords, readButDoNotEvaluate } from './read';
|
27
|
+
import { FragmentReference, Variables } from './FragmentReference';
|
28
|
+
import { areEqualObjectsWithDeepComparison } from './areEqualWithDeepComparison';
|
29
|
+
import { makeNetworkRequest } from './makeNetworkRequest';
|
30
|
+
import { wrapResolvedValue } from './PromiseWrapper';
|
31
|
+
|
32
|
+
const TYPENAME_FIELD_NAME = '__typename';
|
33
|
+
|
34
|
+
export function getOrCreateItemInSuspenseCache<
|
35
|
+
TReadFromStore extends Object,
|
36
|
+
TClientFieldValue,
|
37
|
+
>(
|
38
|
+
environment: IsographEnvironment,
|
39
|
+
index: string,
|
40
|
+
factory: Factory<FragmentReference<TReadFromStore, TClientFieldValue>>,
|
41
|
+
): ParentCache<FragmentReference<TReadFromStore, TClientFieldValue>> {
|
42
|
+
// @ts-expect-error
|
43
|
+
if (typeof window !== 'undefined' && window.__LOG) {
|
44
|
+
console.log('getting cache for', {
|
45
|
+
index,
|
46
|
+
cache: Object.keys(environment.fragmentCache),
|
47
|
+
found: !!environment.fragmentCache[index],
|
48
|
+
});
|
49
|
+
}
|
50
|
+
if (environment.fragmentCache[index] == null) {
|
51
|
+
environment.fragmentCache[index] = new ParentCache(factory);
|
52
|
+
}
|
53
|
+
|
54
|
+
return environment.fragmentCache[index];
|
55
|
+
}
|
56
|
+
|
57
|
+
/**
|
58
|
+
* Creates a copy of the provided value, ensuring any nested objects have their
|
59
|
+
* keys sorted such that equivalent values would have identical JSON.stringify
|
60
|
+
* results.
|
61
|
+
*/
|
62
|
+
export function stableCopy<T>(value: T): T {
|
63
|
+
if (!value || typeof value !== 'object') {
|
64
|
+
return value;
|
65
|
+
}
|
66
|
+
if (Array.isArray(value)) {
|
67
|
+
// @ts-ignore
|
68
|
+
return value.map(stableCopy);
|
69
|
+
}
|
70
|
+
const keys = Object.keys(value).sort();
|
71
|
+
const stable: { [index: string]: any } = {};
|
72
|
+
for (let i = 0; i < keys.length; i++) {
|
73
|
+
// @ts-ignore
|
74
|
+
stable[keys[i]] = stableCopy(value[keys[i]]);
|
75
|
+
}
|
76
|
+
return stable as any;
|
77
|
+
}
|
78
|
+
|
79
|
+
export function getOrCreateCacheForArtifact<
|
80
|
+
TReadFromStore extends Object,
|
81
|
+
TClientFieldValue,
|
82
|
+
>(
|
83
|
+
environment: IsographEnvironment,
|
84
|
+
entrypoint: IsographEntrypoint<TReadFromStore, TClientFieldValue>,
|
85
|
+
variables: Variables,
|
86
|
+
): ParentCache<FragmentReference<TReadFromStore, TClientFieldValue>> {
|
87
|
+
const cacheKey = entrypoint.queryText + JSON.stringify(stableCopy(variables));
|
88
|
+
const factory = () => {
|
89
|
+
const [networkRequest, disposeNetworkRequest] = makeNetworkRequest(
|
90
|
+
environment,
|
91
|
+
entrypoint,
|
92
|
+
variables,
|
93
|
+
);
|
94
|
+
const itemCleanupPair: ItemCleanupPair<
|
95
|
+
FragmentReference<TReadFromStore, TClientFieldValue>
|
96
|
+
> = [
|
97
|
+
{
|
98
|
+
kind: 'FragmentReference',
|
99
|
+
readerWithRefetchQueries: wrapResolvedValue({
|
100
|
+
kind: 'ReaderWithRefetchQueries',
|
101
|
+
readerArtifact: entrypoint.readerWithRefetchQueries.readerArtifact,
|
102
|
+
nestedRefetchQueries:
|
103
|
+
entrypoint.readerWithRefetchQueries.nestedRefetchQueries,
|
104
|
+
}),
|
105
|
+
root: ROOT_ID,
|
106
|
+
variables,
|
107
|
+
networkRequest: networkRequest,
|
108
|
+
},
|
109
|
+
disposeNetworkRequest,
|
110
|
+
];
|
111
|
+
return itemCleanupPair;
|
112
|
+
};
|
113
|
+
return getOrCreateItemInSuspenseCache(environment, cacheKey, factory);
|
114
|
+
}
|
115
|
+
|
116
|
+
type NetworkResponseScalarValue = string | number | boolean;
|
117
|
+
type NetworkResponseValue =
|
118
|
+
| NetworkResponseScalarValue
|
119
|
+
| null
|
120
|
+
| NetworkResponseObject
|
121
|
+
| NetworkResponseObject[]
|
122
|
+
| NetworkResponseScalarValue[];
|
123
|
+
type NetworkResponseObject = {
|
124
|
+
// N.B. undefined is here to support optional id's, but
|
125
|
+
// undefined should not *actually* be present in the network response.
|
126
|
+
[index: string]: undefined | NetworkResponseValue;
|
127
|
+
id?: DataId;
|
128
|
+
};
|
129
|
+
|
130
|
+
export function normalizeData(
|
131
|
+
environment: IsographEnvironment,
|
132
|
+
normalizationAst: NormalizationAst,
|
133
|
+
networkResponse: NetworkResponseObject,
|
134
|
+
variables: Variables,
|
135
|
+
nestedRefetchQueries: RefetchQueryNormalizationArtifactWrapper[],
|
136
|
+
): Set<DataId> {
|
137
|
+
const encounteredIds = new Set<DataId>();
|
138
|
+
|
139
|
+
// @ts-expect-error
|
140
|
+
if (typeof window !== 'undefined' && window.__LOG) {
|
141
|
+
console.log(
|
142
|
+
'about to normalize',
|
143
|
+
normalizationAst,
|
144
|
+
networkResponse,
|
145
|
+
variables,
|
146
|
+
);
|
147
|
+
}
|
148
|
+
normalizeDataIntoRecord(
|
149
|
+
environment,
|
150
|
+
normalizationAst,
|
151
|
+
networkResponse,
|
152
|
+
environment.store.__ROOT,
|
153
|
+
ROOT_ID,
|
154
|
+
variables as any,
|
155
|
+
nestedRefetchQueries,
|
156
|
+
encounteredIds,
|
157
|
+
);
|
158
|
+
// @ts-expect-error
|
159
|
+
if (typeof window !== 'undefined' && window.__LOG) {
|
160
|
+
console.log('after normalization', {
|
161
|
+
store: environment.store,
|
162
|
+
encounteredIds,
|
163
|
+
environment,
|
164
|
+
});
|
165
|
+
}
|
166
|
+
callSubscriptions(environment, encounteredIds);
|
167
|
+
return encounteredIds;
|
168
|
+
}
|
169
|
+
|
170
|
+
export function subscribeToAnyChange(
|
171
|
+
environment: IsographEnvironment,
|
172
|
+
callback: () => void,
|
173
|
+
): () => void {
|
174
|
+
const subscription = {
|
175
|
+
kind: 'AnyRecords',
|
176
|
+
callback,
|
177
|
+
} as const;
|
178
|
+
environment.subscriptions.add(subscription);
|
179
|
+
return () => environment.subscriptions.delete(subscription);
|
180
|
+
}
|
181
|
+
|
182
|
+
// TODO we should re-read and call callback if the value has changed
|
183
|
+
export function subscribe<TReadFromStore extends Object>(
|
184
|
+
environment: IsographEnvironment,
|
185
|
+
encounteredDataAndRecords: WithEncounteredRecords<TReadFromStore>,
|
186
|
+
fragmentReference: FragmentReference<TReadFromStore, any>,
|
187
|
+
callback: (
|
188
|
+
newEncounteredDataAndRecords: WithEncounteredRecords<TReadFromStore>,
|
189
|
+
) => void,
|
190
|
+
): () => void {
|
191
|
+
const fragmentSubscription: FragmentSubscription<TReadFromStore> = {
|
192
|
+
kind: 'FragmentSubscription',
|
193
|
+
callback,
|
194
|
+
encounteredDataAndRecords,
|
195
|
+
fragmentReference,
|
196
|
+
};
|
197
|
+
// @ts-expect-error
|
198
|
+
environment.subscriptions.add(fragmentSubscription);
|
199
|
+
// @ts-expect-error
|
200
|
+
return () => environment.subscriptions.delete(fragmentSubscription);
|
201
|
+
}
|
202
|
+
|
203
|
+
export function onNextChange(environment: IsographEnvironment): Promise<void> {
|
204
|
+
return new Promise((resolve) => {
|
205
|
+
const unsubscribe = subscribeToAnyChange(environment, () => {
|
206
|
+
unsubscribe();
|
207
|
+
resolve();
|
208
|
+
});
|
209
|
+
});
|
210
|
+
}
|
211
|
+
|
212
|
+
// Calls to readButDoNotEvaluate can suspend (i.e. throw a promise).
|
213
|
+
// Maybe in the future, they will be able to throw errors.
|
214
|
+
//
|
215
|
+
// That's probably okay to ignore. We don't, however, want to prevent
|
216
|
+
// updating other subscriptions if one subscription had missing data.
|
217
|
+
function withErrorHandling<T>(f: (t: T) => void): (t: T) => void {
|
218
|
+
return (t) => {
|
219
|
+
try {
|
220
|
+
return f(t);
|
221
|
+
} catch {}
|
222
|
+
};
|
223
|
+
}
|
224
|
+
|
225
|
+
function callSubscriptions(
|
226
|
+
environment: IsographEnvironment,
|
227
|
+
recordsEncounteredWhenNormalizing: Set<DataId>,
|
228
|
+
) {
|
229
|
+
environment.subscriptions.forEach(
|
230
|
+
withErrorHandling((subscription) => {
|
231
|
+
switch (subscription.kind) {
|
232
|
+
case 'FragmentSubscription': {
|
233
|
+
// TODO if there are multiple components subscribed to the same
|
234
|
+
// fragment, we will call readButNotEvaluate multiple times. We
|
235
|
+
// should fix that.
|
236
|
+
if (
|
237
|
+
hasOverlappingIds(
|
238
|
+
recordsEncounteredWhenNormalizing,
|
239
|
+
subscription.encounteredDataAndRecords.encounteredRecords,
|
240
|
+
)
|
241
|
+
) {
|
242
|
+
const newEncounteredDataAndRecords = readButDoNotEvaluate(
|
243
|
+
environment,
|
244
|
+
subscription.fragmentReference,
|
245
|
+
// Is this wrong?
|
246
|
+
// Reasons to think no:
|
247
|
+
// - we are only updating the read-out value, and the network
|
248
|
+
// options only affect whether we throw.
|
249
|
+
// - the component will re-render, and re-throw on its own, anyway.
|
250
|
+
//
|
251
|
+
// Reasons to think not:
|
252
|
+
// - it seems more efficient to suspend here and not update state,
|
253
|
+
// if we expect that the component will just throw anyway
|
254
|
+
// - consistency
|
255
|
+
// - it's also weird, this is called from makeNetworkRequest, where
|
256
|
+
// we don't currently pass network request options
|
257
|
+
{
|
258
|
+
suspendIfInFlight: false,
|
259
|
+
throwOnNetworkError: false,
|
260
|
+
},
|
261
|
+
);
|
262
|
+
|
263
|
+
if (
|
264
|
+
!areEqualObjectsWithDeepComparison(
|
265
|
+
subscription.encounteredDataAndRecords.item,
|
266
|
+
newEncounteredDataAndRecords.item,
|
267
|
+
)
|
268
|
+
) {
|
269
|
+
// @ts-expect-error
|
270
|
+
if (typeof window !== 'undefined' && window.__LOG) {
|
271
|
+
console.log('Deep equality - No', {
|
272
|
+
fragmentReference: subscription.fragmentReference,
|
273
|
+
old: subscription.encounteredDataAndRecords.item,
|
274
|
+
new: newEncounteredDataAndRecords.item,
|
275
|
+
});
|
276
|
+
}
|
277
|
+
// TODO deep compare values
|
278
|
+
subscription.callback(newEncounteredDataAndRecords);
|
279
|
+
} else {
|
280
|
+
// @ts-expect-error
|
281
|
+
if (typeof window !== 'undefined' && window.__LOG) {
|
282
|
+
console.log('Deep equality - Yes', {
|
283
|
+
fragmentReference: subscription.fragmentReference,
|
284
|
+
old: subscription.encounteredDataAndRecords.item,
|
285
|
+
});
|
286
|
+
}
|
287
|
+
}
|
288
|
+
}
|
289
|
+
return;
|
290
|
+
}
|
291
|
+
case 'AnyRecords': {
|
292
|
+
return subscription.callback();
|
293
|
+
}
|
294
|
+
default: {
|
295
|
+
// Ensure we have covered all variants
|
296
|
+
const _: never = subscription;
|
297
|
+
_;
|
298
|
+
throw new Error('Unexpected case');
|
299
|
+
}
|
300
|
+
}
|
301
|
+
}),
|
302
|
+
);
|
303
|
+
}
|
304
|
+
|
305
|
+
function hasOverlappingIds(set1: Set<DataId>, set2: Set<DataId>): boolean {
|
306
|
+
for (const id of set1) {
|
307
|
+
if (set2.has(id)) {
|
308
|
+
return true;
|
309
|
+
}
|
310
|
+
}
|
311
|
+
return false;
|
312
|
+
}
|
313
|
+
|
314
|
+
/**
|
315
|
+
* Mutate targetParentRecord according to the normalizationAst and networkResponseParentRecord.
|
316
|
+
*/
|
317
|
+
function normalizeDataIntoRecord(
|
318
|
+
environment: IsographEnvironment,
|
319
|
+
normalizationAst: NormalizationAst,
|
320
|
+
networkResponseParentRecord: NetworkResponseObject,
|
321
|
+
targetParentRecord: StoreRecord,
|
322
|
+
targetParentRecordId: DataId,
|
323
|
+
variables: Variables,
|
324
|
+
nestedRefetchQueries: RefetchQueryNormalizationArtifactWrapper[],
|
325
|
+
mutableEncounteredIds: Set<DataId>,
|
326
|
+
): RecordHasBeenUpdated {
|
327
|
+
let recordHasBeenUpdated = false;
|
328
|
+
for (const normalizationNode of normalizationAst) {
|
329
|
+
switch (normalizationNode.kind) {
|
330
|
+
case 'Scalar': {
|
331
|
+
const scalarFieldResultedInChange = normalizeScalarField(
|
332
|
+
normalizationNode,
|
333
|
+
networkResponseParentRecord,
|
334
|
+
targetParentRecord,
|
335
|
+
variables,
|
336
|
+
);
|
337
|
+
recordHasBeenUpdated =
|
338
|
+
recordHasBeenUpdated || scalarFieldResultedInChange;
|
339
|
+
break;
|
340
|
+
}
|
341
|
+
case 'Linked': {
|
342
|
+
const linkedFieldResultedInChange = normalizeLinkedField(
|
343
|
+
environment,
|
344
|
+
normalizationNode,
|
345
|
+
networkResponseParentRecord,
|
346
|
+
targetParentRecord,
|
347
|
+
targetParentRecordId,
|
348
|
+
variables,
|
349
|
+
nestedRefetchQueries,
|
350
|
+
mutableEncounteredIds,
|
351
|
+
);
|
352
|
+
recordHasBeenUpdated =
|
353
|
+
recordHasBeenUpdated || linkedFieldResultedInChange;
|
354
|
+
break;
|
355
|
+
}
|
356
|
+
case 'InlineFragment': {
|
357
|
+
const inlineFragmentResultedInChange = normalizeInlineFragment(
|
358
|
+
environment,
|
359
|
+
normalizationNode,
|
360
|
+
networkResponseParentRecord,
|
361
|
+
targetParentRecord,
|
362
|
+
targetParentRecordId,
|
363
|
+
variables,
|
364
|
+
nestedRefetchQueries,
|
365
|
+
mutableEncounteredIds,
|
366
|
+
);
|
367
|
+
recordHasBeenUpdated =
|
368
|
+
recordHasBeenUpdated || inlineFragmentResultedInChange;
|
369
|
+
break;
|
370
|
+
}
|
371
|
+
default: {
|
372
|
+
// Ensure we have covered all variants
|
373
|
+
let _: never = normalizationNode;
|
374
|
+
_;
|
375
|
+
throw new Error('Unexpected normalization node kind');
|
376
|
+
}
|
377
|
+
}
|
378
|
+
}
|
379
|
+
if (recordHasBeenUpdated) {
|
380
|
+
mutableEncounteredIds.add(targetParentRecordId);
|
381
|
+
}
|
382
|
+
return recordHasBeenUpdated;
|
383
|
+
}
|
384
|
+
|
385
|
+
type RecordHasBeenUpdated = boolean;
|
386
|
+
function normalizeScalarField(
|
387
|
+
astNode: NormalizationScalarField,
|
388
|
+
networkResponseParentRecord: NetworkResponseObject,
|
389
|
+
targetStoreRecord: StoreRecord,
|
390
|
+
variables: Variables,
|
391
|
+
): RecordHasBeenUpdated {
|
392
|
+
const networkResponseKey = getNetworkResponseKey(astNode);
|
393
|
+
const networkResponseData = networkResponseParentRecord[networkResponseKey];
|
394
|
+
const parentRecordKey = getParentRecordKey(astNode, variables);
|
395
|
+
|
396
|
+
if (
|
397
|
+
networkResponseData == null ||
|
398
|
+
isScalarOrEmptyArray(networkResponseData)
|
399
|
+
) {
|
400
|
+
const existingValue = targetStoreRecord[parentRecordKey];
|
401
|
+
targetStoreRecord[parentRecordKey] = networkResponseData;
|
402
|
+
return existingValue !== networkResponseData;
|
403
|
+
} else {
|
404
|
+
throw new Error('Unexpected object array when normalizing scalar');
|
405
|
+
}
|
406
|
+
}
|
407
|
+
|
408
|
+
/**
|
409
|
+
* Mutate targetParentRecord with a given linked field ast node.
|
410
|
+
*/
|
411
|
+
function normalizeLinkedField(
|
412
|
+
environment: IsographEnvironment,
|
413
|
+
astNode: NormalizationLinkedField,
|
414
|
+
networkResponseParentRecord: NetworkResponseObject,
|
415
|
+
targetParentRecord: StoreRecord,
|
416
|
+
targetParentRecordId: DataId,
|
417
|
+
variables: Variables,
|
418
|
+
nestedRefetchQueries: RefetchQueryNormalizationArtifactWrapper[],
|
419
|
+
mutableEncounteredIds: Set<DataId>,
|
420
|
+
): RecordHasBeenUpdated {
|
421
|
+
const networkResponseKey = getNetworkResponseKey(astNode);
|
422
|
+
const networkResponseData = networkResponseParentRecord[networkResponseKey];
|
423
|
+
const parentRecordKey = getParentRecordKey(astNode, variables);
|
424
|
+
const existingValue = targetParentRecord[parentRecordKey];
|
425
|
+
|
426
|
+
if (networkResponseData == null) {
|
427
|
+
targetParentRecord[parentRecordKey] = null;
|
428
|
+
return existingValue !== null;
|
429
|
+
}
|
430
|
+
|
431
|
+
if (isScalarButNotEmptyArray(networkResponseData)) {
|
432
|
+
throw new Error(
|
433
|
+
'Unexpected scalar network response when normalizing a linked field',
|
434
|
+
);
|
435
|
+
}
|
436
|
+
|
437
|
+
if (Array.isArray(networkResponseData)) {
|
438
|
+
// TODO check astNode.plural or the like
|
439
|
+
const dataIds: Link[] = [];
|
440
|
+
for (let i = 0; i < networkResponseData.length; i++) {
|
441
|
+
const networkResponseObject = networkResponseData[i];
|
442
|
+
const newStoreRecordId = normalizeNetworkResponseObject(
|
443
|
+
environment,
|
444
|
+
astNode,
|
445
|
+
networkResponseObject,
|
446
|
+
targetParentRecordId,
|
447
|
+
variables,
|
448
|
+
i,
|
449
|
+
nestedRefetchQueries,
|
450
|
+
mutableEncounteredIds,
|
451
|
+
);
|
452
|
+
|
453
|
+
dataIds.push({ __link: newStoreRecordId });
|
454
|
+
}
|
455
|
+
targetParentRecord[parentRecordKey] = dataIds;
|
456
|
+
return !dataIdsAreTheSame(existingValue, dataIds);
|
457
|
+
} else {
|
458
|
+
const newStoreRecordId = normalizeNetworkResponseObject(
|
459
|
+
environment,
|
460
|
+
astNode,
|
461
|
+
networkResponseData,
|
462
|
+
targetParentRecordId,
|
463
|
+
variables,
|
464
|
+
null,
|
465
|
+
nestedRefetchQueries,
|
466
|
+
mutableEncounteredIds,
|
467
|
+
);
|
468
|
+
|
469
|
+
targetParentRecord[parentRecordKey] = {
|
470
|
+
__link: newStoreRecordId,
|
471
|
+
};
|
472
|
+
const link = getLink(existingValue);
|
473
|
+
return link?.__link !== newStoreRecordId;
|
474
|
+
}
|
475
|
+
}
|
476
|
+
|
477
|
+
/**
|
478
|
+
* Mutate targetParentRecord with a given linked field ast node.
|
479
|
+
*/
|
480
|
+
function normalizeInlineFragment(
|
481
|
+
environment: IsographEnvironment,
|
482
|
+
astNode: NormalizationInlineFragment,
|
483
|
+
networkResponseParentRecord: NetworkResponseObject,
|
484
|
+
targetParentRecord: StoreRecord,
|
485
|
+
targetParentRecordId: DataId,
|
486
|
+
variables: Variables,
|
487
|
+
nestedRefetchQueries: RefetchQueryNormalizationArtifactWrapper[],
|
488
|
+
mutableEncounteredIds: Set<DataId>,
|
489
|
+
): RecordHasBeenUpdated {
|
490
|
+
const typeToRefineTo = astNode.type;
|
491
|
+
if (networkResponseParentRecord[TYPENAME_FIELD_NAME] === typeToRefineTo) {
|
492
|
+
const hasBeenModified = normalizeDataIntoRecord(
|
493
|
+
environment,
|
494
|
+
astNode.selections,
|
495
|
+
networkResponseParentRecord,
|
496
|
+
targetParentRecord,
|
497
|
+
targetParentRecordId,
|
498
|
+
variables,
|
499
|
+
nestedRefetchQueries,
|
500
|
+
mutableEncounteredIds,
|
501
|
+
);
|
502
|
+
return hasBeenModified;
|
503
|
+
}
|
504
|
+
return false;
|
505
|
+
}
|
506
|
+
|
507
|
+
function dataIdsAreTheSame(
|
508
|
+
existingValue: DataTypeValue,
|
509
|
+
newDataIds: Link[],
|
510
|
+
): boolean {
|
511
|
+
if (Array.isArray(existingValue)) {
|
512
|
+
if (newDataIds.length !== existingValue.length) {
|
513
|
+
return false;
|
514
|
+
}
|
515
|
+
for (let i = 0; i < newDataIds.length; i++) {
|
516
|
+
const maybeLink = getLink(existingValue[i]);
|
517
|
+
if (maybeLink !== null) {
|
518
|
+
if (newDataIds[i].__link !== maybeLink.__link) {
|
519
|
+
return false;
|
520
|
+
}
|
521
|
+
}
|
522
|
+
}
|
523
|
+
return true;
|
524
|
+
} else {
|
525
|
+
return false;
|
526
|
+
}
|
527
|
+
}
|
528
|
+
|
529
|
+
function normalizeNetworkResponseObject(
|
530
|
+
environment: IsographEnvironment,
|
531
|
+
astNode: NormalizationLinkedField,
|
532
|
+
networkResponseData: NetworkResponseObject,
|
533
|
+
targetParentRecordId: string,
|
534
|
+
variables: Variables,
|
535
|
+
index: number | null,
|
536
|
+
nestedRefetchQueries: RefetchQueryNormalizationArtifactWrapper[],
|
537
|
+
mutableEncounteredIds: Set<DataId>,
|
538
|
+
): DataId /* The id of the modified or newly created item */ {
|
539
|
+
const newStoreRecordId = getDataIdOfNetworkResponse(
|
540
|
+
targetParentRecordId,
|
541
|
+
networkResponseData,
|
542
|
+
astNode,
|
543
|
+
variables,
|
544
|
+
index,
|
545
|
+
);
|
546
|
+
|
547
|
+
const newStoreRecord = environment.store[newStoreRecordId] ?? {};
|
548
|
+
environment.store[newStoreRecordId] = newStoreRecord;
|
549
|
+
|
550
|
+
normalizeDataIntoRecord(
|
551
|
+
environment,
|
552
|
+
astNode.selections,
|
553
|
+
networkResponseData,
|
554
|
+
newStoreRecord,
|
555
|
+
newStoreRecordId,
|
556
|
+
variables,
|
557
|
+
nestedRefetchQueries,
|
558
|
+
mutableEncounteredIds,
|
559
|
+
);
|
560
|
+
|
561
|
+
return newStoreRecordId;
|
562
|
+
}
|
563
|
+
|
564
|
+
function isScalarOrEmptyArray(
|
565
|
+
data: NonNullable<NetworkResponseValue>,
|
566
|
+
): data is NetworkResponseScalarValue | NetworkResponseScalarValue[] {
|
567
|
+
// N.B. empty arrays count as empty arrays of scalar fields.
|
568
|
+
if (Array.isArray(data)) {
|
569
|
+
// This is maybe fixed in a new version of Typescript??
|
570
|
+
return (data as any).every((x: any) => isScalarOrEmptyArray(x));
|
571
|
+
}
|
572
|
+
const isScalarValue =
|
573
|
+
typeof data === 'string' ||
|
574
|
+
typeof data === 'number' ||
|
575
|
+
typeof data === 'boolean';
|
576
|
+
return isScalarValue;
|
577
|
+
}
|
578
|
+
|
579
|
+
function isScalarButNotEmptyArray(
|
580
|
+
data: NonNullable<NetworkResponseValue>,
|
581
|
+
): data is NetworkResponseScalarValue | NetworkResponseScalarValue[] {
|
582
|
+
// N.B. empty arrays count as empty arrays of linked fields.
|
583
|
+
if (Array.isArray(data)) {
|
584
|
+
if (data.length === 0) {
|
585
|
+
return false;
|
586
|
+
}
|
587
|
+
// This is maybe fixed in a new version of Typescript??
|
588
|
+
return (data as any).every((x: any) => isScalarOrEmptyArray(x));
|
589
|
+
}
|
590
|
+
const isScalarValue =
|
591
|
+
typeof data === 'string' ||
|
592
|
+
typeof data === 'number' ||
|
593
|
+
typeof data === 'boolean';
|
594
|
+
return isScalarValue;
|
595
|
+
}
|
596
|
+
|
597
|
+
export function getParentRecordKey(
|
598
|
+
astNode:
|
599
|
+
| NormalizationLinkedField
|
600
|
+
| NormalizationScalarField
|
601
|
+
| ReaderLinkedField
|
602
|
+
| ReaderScalarField,
|
603
|
+
variables: Variables,
|
604
|
+
): string {
|
605
|
+
let parentRecordKey = astNode.fieldName;
|
606
|
+
const fieldParameters = astNode.arguments;
|
607
|
+
if (fieldParameters != null) {
|
608
|
+
for (const fieldParameter of fieldParameters) {
|
609
|
+
parentRecordKey += getStoreKeyChunkForArgument(fieldParameter, variables);
|
610
|
+
}
|
611
|
+
}
|
612
|
+
|
613
|
+
return parentRecordKey;
|
614
|
+
}
|
615
|
+
|
616
|
+
function getStoreKeyChunkForArgumentValue(
|
617
|
+
argumentValue: ArgumentValue,
|
618
|
+
variables: Variables,
|
619
|
+
) {
|
620
|
+
switch (argumentValue.kind) {
|
621
|
+
case 'Literal': {
|
622
|
+
return argumentValue.value;
|
623
|
+
}
|
624
|
+
case 'Variable': {
|
625
|
+
return variables[argumentValue.name] ?? 'null';
|
626
|
+
}
|
627
|
+
case 'String': {
|
628
|
+
return argumentValue.value;
|
629
|
+
}
|
630
|
+
case 'Enum': {
|
631
|
+
return argumentValue.value;
|
632
|
+
}
|
633
|
+
default: {
|
634
|
+
// TODO configure eslint to allow unused vars starting with _
|
635
|
+
// Ensure we have covered all variants
|
636
|
+
const _: never = argumentValue;
|
637
|
+
_;
|
638
|
+
throw new Error('Unexpected case');
|
639
|
+
}
|
640
|
+
}
|
641
|
+
}
|
642
|
+
|
643
|
+
function getStoreKeyChunkForArgument(argument: Argument, variables: Variables) {
|
644
|
+
const chunk = getStoreKeyChunkForArgumentValue(argument[1], variables);
|
645
|
+
return `${FIRST_SPLIT_KEY}${argument[0]}${SECOND_SPLIT_KEY}${chunk}`;
|
646
|
+
}
|
647
|
+
|
648
|
+
function getNetworkResponseKey(
|
649
|
+
astNode: NormalizationLinkedField | NormalizationScalarField,
|
650
|
+
): string {
|
651
|
+
let networkResponseKey = astNode.fieldName;
|
652
|
+
const fieldParameters = astNode.arguments;
|
653
|
+
if (fieldParameters != null) {
|
654
|
+
for (const fieldParameter of fieldParameters) {
|
655
|
+
const [argumentName, argumentValue] = fieldParameter;
|
656
|
+
let argumentValueChunk;
|
657
|
+
switch (argumentValue.kind) {
|
658
|
+
case 'Literal': {
|
659
|
+
argumentValueChunk = 'l_' + argumentValue.value;
|
660
|
+
break;
|
661
|
+
}
|
662
|
+
case 'Variable': {
|
663
|
+
argumentValueChunk = 'v_' + argumentValue.name;
|
664
|
+
break;
|
665
|
+
}
|
666
|
+
case 'String': {
|
667
|
+
argumentValueChunk = 's_' + argumentValue.value;
|
668
|
+
break;
|
669
|
+
}
|
670
|
+
case 'Enum': {
|
671
|
+
argumentValueChunk = 'e_' + argumentValue.value;
|
672
|
+
break;
|
673
|
+
}
|
674
|
+
default: {
|
675
|
+
// Ensure we have covered all variants
|
676
|
+
let _: never = argumentValue;
|
677
|
+
_;
|
678
|
+
throw new Error('Unexpected case');
|
679
|
+
}
|
680
|
+
}
|
681
|
+
networkResponseKey += `${FIRST_SPLIT_KEY}${argumentName}${SECOND_SPLIT_KEY}${argumentValueChunk}`;
|
682
|
+
}
|
683
|
+
}
|
684
|
+
return networkResponseKey;
|
685
|
+
}
|
686
|
+
|
687
|
+
// an alias might be pullRequests____first___first____after___cursor
|
688
|
+
export const FIRST_SPLIT_KEY = '____';
|
689
|
+
export const SECOND_SPLIT_KEY = '___';
|
690
|
+
|
691
|
+
// Returns a key to look up an item in the store
|
692
|
+
function getDataIdOfNetworkResponse(
|
693
|
+
parentRecordId: DataId,
|
694
|
+
dataToNormalize: NetworkResponseObject,
|
695
|
+
astNode: NormalizationLinkedField | NormalizationScalarField,
|
696
|
+
variables: Variables,
|
697
|
+
index: number | null,
|
698
|
+
): DataId {
|
699
|
+
// Check whether the dataToNormalize has an id field. If so, that is the key.
|
700
|
+
// If not, we construct an id from the parentRecordId and the field parameters.
|
701
|
+
|
702
|
+
const dataId = dataToNormalize.id;
|
703
|
+
if (dataId != null) {
|
704
|
+
return dataId;
|
705
|
+
}
|
706
|
+
|
707
|
+
let storeKey = `${parentRecordId}.${astNode.fieldName}`;
|
708
|
+
if (index != null) {
|
709
|
+
storeKey += `.${index}`;
|
710
|
+
}
|
711
|
+
|
712
|
+
const fieldParameters = astNode.arguments;
|
713
|
+
if (fieldParameters == null) {
|
714
|
+
return storeKey;
|
715
|
+
}
|
716
|
+
|
717
|
+
for (const fieldParameter of fieldParameters) {
|
718
|
+
storeKey += getStoreKeyChunkForArgument(fieldParameter, variables);
|
719
|
+
}
|
720
|
+
return storeKey;
|
721
|
+
}
|