Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helper methods for Relay Modern updater
// @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
You can’t perform that action at this time.