-
-
Save tlvenn/4818de291d88636e492e7fdc909cd1a1 to your computer and use it in GitHub Desktop.
Helper methods for Relay Modern updater
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @flow | |
import { ConnectionHandler } from 'relay-runtime'; | |
import { isObject, isArray } from 'lodash/fp'; | |
export function listRecordRemoveUpdater({ parentId, itemId, parentFieldName, store }) { | |
const parentProxy = store.get(parentId); | |
const items = parentProxy.getLinkedRecords(parentFieldName); | |
parentProxy.setLinkedRecords(items.filter(record => record._dataID !== itemId), parentFieldName); | |
} | |
export function listRecordAddUpdater({ parentId, item, type, parentFieldName, store }) { | |
const node = store.create(item.id, type); | |
Object.keys(item).forEach(key => { | |
node.setValue(item[key], key); | |
}); | |
const parentProxy = store.get(parentId); | |
const items = parentProxy.getLinkedRecords(parentFieldName); | |
parentProxy.setLinkedRecords([...items, node], parentFieldName); | |
} | |
export function connectionUpdater(store, parentId, connectionName, edge, before = false) { | |
if (edge) { | |
const parentProxy = store.get(parentId); | |
const conn = ConnectionHandler.getConnection(parentProxy, connectionName); | |
if (!conn) { | |
return; | |
} | |
if (before) { | |
ConnectionHandler.insertEdgeBefore(conn, edge); | |
} else { | |
ConnectionHandler.insertEdgeAfter(conn, edge); | |
} | |
} | |
} | |
export function optimisticConnectionUpdater({ | |
parentId, | |
store, | |
connectionName, | |
item, | |
customNode, | |
itemType, | |
}) { | |
const node = customNode || store.create(item.id, itemType); | |
!customNode && | |
Object.keys(item).forEach(key => { | |
node.setValue(item[key], key); | |
}); | |
const edge = store.create('client:newEdge:' + node._dataID.match(/[^:]+$/)[0], `${itemType}Edge`); | |
edge.setLinkedRecord(node, 'node'); | |
connectionUpdater({ edge, parentId, store, connectionName }); | |
} | |
export function connectionDeleteEdgeUpdater({ parentId, connectionName, nodeId, store }) { | |
const parentProxy = store.get(parentId); | |
const conn = ConnectionHandler.getConnection(parentProxy, connectionName); | |
if (!conn) { | |
console.warn(`Connection ${connectionName} not found on ${parentId}`); | |
return; | |
} | |
ConnectionHandler.deleteNode(conn, nodeId); | |
} | |
export function copyObjScalarsToProxy({ object, proxy }) { | |
Object.keys(object).forEach(key => { | |
if (isObject(object[key]) || isArray(object[key])) return; | |
proxy.setValue(object[key], key); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment