UNPKG

@airbnb/lunar-apollo

Version:

Apollo and GraphQL utilities.

35 lines (30 loc) 1.43 kB
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } import { get, set } from 'lodash/fp'; import prepareQuery from '../utils/prepareQuery'; import getQueryName from '../utils/getQueryName'; export default function addToList(docOrQuery, listPath, mutationPath) { const query = prepareQuery(docOrQuery); return (cache, mutationResult) => { const queryResult = cache.readQuery(query); const list = get(listPath, queryResult); if (typeof list === 'undefined' || !Array.isArray(list)) { if ("production" !== process.env.NODE_ENV) { throw new TypeError("\"" + getQueryName(query.query) + "\" list \"" + listPath + "\" is not an array."); } else { return; } } const data = get(mutationPath, mutationResult); if (typeof data === 'undefined') { if ("production" !== process.env.NODE_ENV) { throw new Error("Cannot find mutation \"" + mutationPath + "\". Unable to update query list."); } else { return; } } const nextResult = set(listPath, [...list, data], _extends({}, queryResult)); cache.writeQuery(_extends({}, query, { data: nextResult })); }; }