-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathConnectionHandler.js
More file actions
617 lines (589 loc) · 17.7 KB
/
ConnectionHandler.js
File metadata and controls
617 lines (589 loc) · 17.7 KB
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
* @oncall relay
*/
'use strict';
import type {
HandleFieldPayload,
ReadOnlyRecordProxy,
RecordProxy,
RecordSourceProxy,
} from '../../store/RelayStoreTypes';
import type {DataID, Variables} from '../../util/RelayRuntimeTypes';
const {generateClientID} = require('../../store/ClientID');
const {getStableStorageKey} = require('../../store/RelayStoreUtils');
const getRelayHandleKey = require('../../util/getRelayHandleKey');
const ConnectionInterface = require('./ConnectionInterface');
const invariant = require('invariant');
const warning = require('warning');
export type ConnectionMetadata = {
path: ?Array<string>,
direction: ?('forward' | 'backward' | 'bidirectional'),
cursor: ?string,
count: ?string,
stream?: boolean,
...
};
const CONNECTION = 'connection';
// Per-instance incrementing index used to generate unique edge IDs
const NEXT_EDGE_INDEX = '__connection_next_edge_index';
/**
* @public
*
* A default runtime handler for connection fields that appends newly fetched
* edges onto the end of a connection, regardless of the arguments used to fetch
* those edges.
*/
function update(store: RecordSourceProxy, payload: HandleFieldPayload): void {
const record = store.get(payload.dataID);
if (!record) {
return;
}
const {
EDGES,
END_CURSOR,
HAS_NEXT_PAGE,
HAS_PREV_PAGE,
PAGE_INFO,
PAGE_INFO_TYPE,
START_CURSOR,
} = ConnectionInterface.get();
const serverConnection = record.getLinkedRecord(payload.fieldKey);
const serverPageInfo =
serverConnection && serverConnection.getLinkedRecord(PAGE_INFO);
if (!serverConnection) {
record.setValue(
null,
payload.handleKey,
undefined,
record.getErrors(payload.fieldKey),
);
return;
}
// In rare cases the handleKey field may be unset even though the client
// connection record exists, in this case new edges should still be merged
// into the existing client connection record (and the field reset to point
// to that record).
const clientConnectionID = generateClientID(
record.getDataID(),
payload.handleKey,
);
const clientConnectionField = record.getLinkedRecord(payload.handleKey);
const clientConnection =
clientConnectionField ?? store.get(clientConnectionID);
let clientPageInfo =
clientConnection && clientConnection.getLinkedRecord(PAGE_INFO);
if (!clientConnection) {
// Initial fetch with data: copy fields from the server record
const connection = store.create(
clientConnectionID,
serverConnection.getType(),
);
connection.setValue(0, NEXT_EDGE_INDEX);
connection.copyFieldsFrom(serverConnection);
let serverEdges = serverConnection.getLinkedRecords(EDGES);
if (serverEdges) {
serverEdges = serverEdges.map(edge =>
buildConnectionEdge(store, connection, edge),
);
connection.setLinkedRecords(serverEdges, EDGES);
}
record.setLinkedRecord(connection, payload.handleKey);
clientPageInfo = store.create(
generateClientID(connection.getDataID(), PAGE_INFO),
PAGE_INFO_TYPE,
);
clientPageInfo.setValue(false, HAS_NEXT_PAGE);
clientPageInfo.setValue(false, HAS_PREV_PAGE);
clientPageInfo.setValue(null, END_CURSOR);
clientPageInfo.setValue(null, START_CURSOR);
if (serverPageInfo) {
clientPageInfo.copyFieldsFrom(serverPageInfo);
}
connection.setLinkedRecord(clientPageInfo, PAGE_INFO);
} else {
if (clientConnectionField == null) {
// If the handleKey field was unset but the client connection record
// existed, update the field to point to the record
record.setLinkedRecord(clientConnection, payload.handleKey);
}
const connection = clientConnection;
// Subsequent fetches:
// - updated fields on the connection
// - merge prev/next edges, de-duplicating by node id
// - synthesize page info fields
let serverEdges = serverConnection.getLinkedRecords(EDGES);
if (serverEdges) {
serverEdges = serverEdges.map(edge =>
buildConnectionEdge(store, connection, edge),
);
}
const prevEdges = connection.getLinkedRecords(EDGES);
const prevPageInfo = connection.getLinkedRecord(PAGE_INFO);
connection.copyFieldsFrom(serverConnection);
// Reset EDGES and PAGE_INFO fields
if (prevEdges) {
connection.setLinkedRecords(prevEdges, EDGES);
}
if (prevPageInfo) {
connection.setLinkedRecord(prevPageInfo, PAGE_INFO);
}
let nextEdges: Array<?RecordProxy> = [];
const args = payload.args;
if (prevEdges && serverEdges) {
if (args.after != null) {
const clientEndCursor = clientPageInfo?.getValue(END_CURSOR);
const serverEndCursor = serverPageInfo?.getValue(END_CURSOR);
const isAddingEdgesAfterCurrentPage =
clientPageInfo && args.after === clientEndCursor;
const isFillingOutCurrentPage =
clientPageInfo && clientEndCursor === serverEndCursor;
// Forward pagination from the end of the connection: append edges
// Case 1: We're fetching edges for the first time and pageInfo for
// the upcoming page is missing, but our after cursor matches
// the last ending cursor. (adding after current page)
// Case 2: We've fetched these edges before and we know the end cursor
// from the first edge updating the END_CURSOR field. If the
// end cursor from the server matches the end cursor from the
// client then we're just filling out the rest of this page.
if (isAddingEdgesAfterCurrentPage || isFillingOutCurrentPage) {
const nodeIDs = new Set<unknown>();
mergeEdges(prevEdges, nextEdges, nodeIDs);
mergeEdges(serverEdges, nextEdges, nodeIDs);
} else {
warning(
false,
'Relay: Unexpected after cursor `%s`, edges must ' +
'be fetched from the end of the list (`%s`).',
args.after,
clientPageInfo && clientPageInfo.getValue(END_CURSOR),
);
return;
}
} else if (args.before != null) {
// Backward pagination from the start of the connection: prepend edges
if (
clientPageInfo &&
args.before === clientPageInfo.getValue(START_CURSOR)
) {
const nodeIDs = new Set<unknown>();
mergeEdges(serverEdges, nextEdges, nodeIDs);
mergeEdges(prevEdges, nextEdges, nodeIDs);
} else {
warning(
false,
'Relay: Unexpected before cursor `%s`, edges must ' +
'be fetched from the beginning of the list (`%s`).',
args.before,
clientPageInfo && clientPageInfo.getValue(START_CURSOR),
);
return;
}
} else {
// The connection was refetched from the beginning/end: replace edges
nextEdges = serverEdges;
}
} else if (serverEdges) {
nextEdges = serverEdges;
} else {
// $FlowFixMe[incompatible-type]
nextEdges = prevEdges;
}
// Update edges only if they were updated, the null check is
// for Flow (prevEdges could be null).
if (nextEdges != null && nextEdges !== prevEdges) {
connection.setLinkedRecords(nextEdges, EDGES);
}
// Page info should be updated even if no new edge were returned.
if (clientPageInfo && serverPageInfo) {
if (args.after == null && args.before == null) {
// The connection was refetched from the beginning/end: replace
// page_info
clientPageInfo.copyFieldsFrom(serverPageInfo);
} else if (args.before != null || (args.after == null && args.last)) {
clientPageInfo.setValue(
!!serverPageInfo.getValue(HAS_PREV_PAGE),
HAS_PREV_PAGE,
);
const startCursor = serverPageInfo.getValue(START_CURSOR);
if (typeof startCursor === 'string') {
clientPageInfo.setValue(startCursor, START_CURSOR);
}
} else if (args.after != null || (args.before == null && args.first)) {
clientPageInfo.setValue(
!!serverPageInfo.getValue(HAS_NEXT_PAGE),
HAS_NEXT_PAGE,
);
const endCursor = serverPageInfo.getValue(END_CURSOR);
if (typeof endCursor === 'string') {
clientPageInfo.setValue(endCursor, END_CURSOR);
}
}
}
}
}
/**
* @public
*
* Given a record and the name of the schema field for which a connection was
* fetched, returns the linked connection record.
*
* Example:
*
* Given that data has already been fetched on some user `<id>` on the `friends`
* field:
*
* ```
* fragment FriendsFragment on User {
* friends(first: 10) @connection(key: "FriendsFragment_friends") {
* edges {
* node {
* id
* }
* }
* }
* }
* ```
*
* The `friends` connection record can be accessed with:
*
* ```
* store => {
* const user = store.get('<id>');
* const friends = ConnectionHandler.getConnection(user, 'FriendsFragment_friends');
* // Access fields on the connection:
* const edges = friends.getLinkedRecords('edges');
* }
* ```
*
* TODO: t15733312
* Currently we haven't run into this case yet, but we need to add a `getConnections`
* that returns an array of the connections under the same `key` regardless of the variables.
*/
function getConnection(
record: ReadOnlyRecordProxy,
key: string,
filters?: ?Variables,
): ?RecordProxy {
const handleKey = getRelayHandleKey(CONNECTION, key, null);
return record.getLinkedRecord(handleKey, filters);
}
/**
* @public
*
* Given a record ID, the key of a connection field, and optional filters used
* to identify the connection, returns the connection ID.
*
* Example:
*
* Given that data has already been fetched on some user `<user-id>` on the `friends`
* field:
*
* ```
* fragment FriendsFragment on User {
* friends(first: 10) @connection(key: "FriendsFragment_friends") {
* edges {
* node {
* id
* }
* }
* }
* }
* ```
*
* The ID of the `friends` connection record can be accessed with:
*
* ```
* store => {
* const connectionID = ConnectionHandler.getConnectionID('<user-id>', 'FriendsFragment_friends');
* }
* ```
*/
function getConnectionID(
recordID: DataID,
key: string,
filters?: ?Variables,
): DataID {
const handleKey = getRelayHandleKey(CONNECTION, key, null);
const storageKey = getStableStorageKey(handleKey, filters);
return generateClientID(recordID, storageKey);
}
/**
* @public
*
* Inserts an edge after the given cursor, or at the end of the list if no
* cursor is provided.
*
* Example:
*
* Given that data has already been fetched on some user `<id>` on the `friends`
* field:
*
* ```
* fragment FriendsFragment on User {
* friends(first: 10) @connection(key: "FriendsFragment_friends") {
* edges {
* node {
* id
* }
* }
* }
* }
* ```
*
* An edge can be appended with:
*
* ```
* store => {
* const user = store.get('<id>');
* const friends = ConnectionHandler.getConnection(user, 'FriendsFragment_friends');
* const edge = store.create('<edge-id>', 'FriendsEdge');
* ConnectionHandler.insertEdgeAfter(friends, edge);
* }
* ```
*/
function insertEdgeAfter(
record: RecordProxy,
newEdge: RecordProxy,
cursor?: ?string,
): void {
const {CURSOR, EDGES} = ConnectionInterface.get();
const edges = record.getLinkedRecords(EDGES);
if (!edges) {
record.setLinkedRecords([newEdge], EDGES);
return;
}
let nextEdges;
if (cursor == null) {
nextEdges = edges.concat(newEdge);
} else {
nextEdges = [] as Array<?RecordProxy>;
let foundCursor = false;
for (let ii = 0; ii < edges.length; ii++) {
const edge = edges[ii];
nextEdges.push(edge);
if (edge == null) {
continue;
}
const edgeCursor = edge.getValue(CURSOR);
if (cursor === edgeCursor) {
nextEdges.push(newEdge);
foundCursor = true;
}
}
if (!foundCursor) {
nextEdges.push(newEdge);
}
}
record.setLinkedRecords(nextEdges, EDGES);
}
/**
* @public
*
* Creates an edge for a connection record, given a node and edge type.
*/
function createEdge(
store: RecordSourceProxy,
record: RecordProxy,
node: RecordProxy,
edgeType: string,
): RecordProxy {
const {NODE} = ConnectionInterface.get();
// An index-based client ID could easily conflict (unless it was
// auto-incrementing, but there is nowhere to the store the id)
// Instead, construct a client ID based on the connection ID and node ID,
// which will only conflict if the same node is added to the same connection
// twice. This is acceptable since the `insertEdge*` functions ignore
// duplicates.
const edgeID = generateClientID(record.getDataID(), node.getDataID());
let edge = store.get(edgeID);
if (!edge) {
edge = store.create(edgeID, edgeType);
}
edge.setLinkedRecord(node, NODE);
if (edge.getValue('cursor') == null) {
// Always use null instead of undefined value for cursor
// to avoid considering it as missing data
edge.setValue(null, 'cursor');
}
return edge;
}
/**
* @public
*
* Inserts an edge before the given cursor, or at the beginning of the list if
* no cursor is provided.
*
* Example:
*
* Given that data has already been fetched on some user `<id>` on the `friends`
* field:
*
* ```
* fragment FriendsFragment on User {
* friends(first: 10) @connection(key: "FriendsFragment_friends") {
* edges {
* node {
* id
* }
* }
* }
* }
* ```
*
* An edge can be prepended with:
*
* ```
* store => {
* const user = store.get('<id>');
* const friends = ConnectionHandler.getConnection(user, 'FriendsFragment_friends');
* const edge = store.create('<edge-id>', 'FriendsEdge');
* ConnectionHandler.insertEdgeBefore(friends, edge);
* }
* ```
*/
function insertEdgeBefore(
record: RecordProxy,
newEdge: RecordProxy,
cursor?: ?string,
): void {
const {CURSOR, EDGES} = ConnectionInterface.get();
const edges = record.getLinkedRecords(EDGES);
if (!edges) {
record.setLinkedRecords([newEdge], EDGES);
return;
}
let nextEdges;
if (cursor == null) {
nextEdges = [newEdge].concat(edges);
} else {
nextEdges = [] as Array<?RecordProxy>;
let foundCursor = false;
for (let ii = 0; ii < edges.length; ii++) {
const edge = edges[ii];
if (edge != null) {
const edgeCursor = edge.getValue(CURSOR);
if (cursor === edgeCursor) {
nextEdges.push(newEdge);
foundCursor = true;
}
}
nextEdges.push(edge);
}
if (!foundCursor) {
nextEdges.unshift(newEdge);
}
}
record.setLinkedRecords(nextEdges, EDGES);
}
/**
* @public
*
* Remove any edges whose `node.id` matches the given id.
*/
function deleteNode(record: RecordProxy, nodeID: DataID): void {
const {EDGES, NODE} = ConnectionInterface.get();
const edges = record.getLinkedRecords(EDGES);
if (!edges) {
return;
}
let nextEdges;
for (let ii = 0; ii < edges.length; ii++) {
const edge = edges[ii];
const node = edge && edge.getLinkedRecord(NODE);
if (node != null && node.getDataID() === nodeID) {
if (nextEdges === undefined) {
nextEdges = edges.slice(0, ii);
}
} else if (nextEdges !== undefined) {
nextEdges.push(edge);
}
}
if (nextEdges !== undefined) {
record.setLinkedRecords(nextEdges, EDGES);
}
}
/**
* @internal
*
* Creates a copy of an edge with a unique ID based on per-connection-instance
* incrementing edge index. This is necessary to avoid collisions between edges,
* which can occur because (edge) client IDs are assigned deterministically
* based on the path from the nearest node with an id.
*
* Example: if the first N edges of the same connection are refetched, the edges
* from the second fetch will be assigned the same IDs as the first fetch, even
* though the nodes they point to may be different (or the same and in different
* order).
*/
function buildConnectionEdge(
store: RecordSourceProxy,
connection: RecordProxy,
edge: ?RecordProxy,
): ?RecordProxy {
if (edge == null) {
return edge;
}
const {EDGES} = ConnectionInterface.get();
const edgeIndex = connection.getValue(NEXT_EDGE_INDEX);
invariant(
typeof edgeIndex === 'number',
'ConnectionHandler: Expected %s to be a number, got `%s`.',
NEXT_EDGE_INDEX,
edgeIndex,
);
const edgeID = generateClientID(connection.getDataID(), EDGES, edgeIndex);
const connectionEdge = store.create(edgeID, edge.getType());
connectionEdge.copyFieldsFrom(edge);
if (connectionEdge.getValue('cursor') == null) {
// Always use null instead of undefined value for cursor
// to avoid considering it as missing data
connectionEdge.setValue(null, 'cursor');
}
connection.setValue(edgeIndex + 1, NEXT_EDGE_INDEX);
return connectionEdge;
}
/**
* @internal
*
* Adds the source edges to the target edges, skipping edges with
* duplicate node ids.
*/
function mergeEdges(
sourceEdges: Array<?RecordProxy>,
targetEdges: Array<?RecordProxy>,
nodeIDs: Set<unknown>,
): void {
const {NODE} = ConnectionInterface.get();
for (let ii = 0; ii < sourceEdges.length; ii++) {
const edge = sourceEdges[ii];
if (!edge) {
continue;
}
const node = edge.getLinkedRecord(NODE);
const nodeID = node && node.getDataID();
if (nodeID) {
if (nodeIDs.has(nodeID)) {
continue;
}
nodeIDs.add(nodeID);
}
targetEdges.push(edge);
}
}
module.exports = {
buildConnectionEdge,
createEdge,
deleteNode,
getConnection,
getConnectionID,
insertEdgeAfter,
insertEdgeBefore,
update,
};