/
connection.js
79 lines (70 loc) · 1.54 KB
/
connection.js
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
// @flow
import {
find,
findIndex,
lensIndex,
lensPath,
pathEq,
propEq,
set,
view,
} from 'ramda';
import {
cursorForObjectInConnection as cursorForObjectInConnectionOrig,
offsetToCursor,
} from 'graphql-relay';
export type Edge = {
node: Object,
};
export type Connection = {
cursor?: string,
edges: Array<?Edge>,
};
const findEdgeIndex = (id, edges) => {
return findIndex(pathEq(['node', 'id'], id), edges);
};
/**
* Replaces an edge in a list
*
* @param data
* @param edgePath
* @param edge
* @returns {*}
*/
export const replaceEdge = (
data: any,
edgePath: Array<string>,
edge: Object,
) => {
// $FlowFixMe$
const edgesPath = lensPath(edgePath);
const oldEdges = view(edgesPath, data);
const edgeIndex = findEdgeIndex(edge.node.id, oldEdges);
const indexLens = lensIndex(edgeIndex);
if (edgeIndex !== -1) {
const newEdges = set(indexLens, edge, oldEdges);
return set(edgesPath, newEdges, data);
}
return null;
};
/**
* Modified version of cursorForObjectInConnection which uses primary ID as well
*
* @param connection
* @param obj
* @returns {*}
*/
export const cursorForObjectInConnection = (
connection: Array<Object>,
obj: Object,
) => {
const cursor = cursorForObjectInConnectionOrig(connection, obj);
// try to find by ID if the original fails
if (!cursor && obj.id) {
const objInConnectionById = find(propEq('id', obj.id))(connection);
if (objInConnectionById) {
return offsetToCursor(connection.indexOf(objInConnectionById));
}
}
return cursor;
};