Skip to content

Instantly share code, notes, and snippets.

@JCMais
Forked from sibelius/MutationUtils.js
Created March 20, 2018 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JCMais/8ea68184cc9ec85cd4c11537ca86c52c to your computer and use it in GitHub Desktop.
Save JCMais/8ea68184cc9ec85cd4c11537ca86c52c to your computer and use it in GitHub Desktop.
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