@airbnb/lunar-apollo
Version:
Apollo and GraphQL utilities.
39 lines (32 loc) • 1.48 kB
JavaScript
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 from 'lodash/get';
import set from 'lodash/set';
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 nextResult = _extends({}, queryResult);
const list = get(queryResult, listPath);
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(mutationResult.data, mutationPath);
if (typeof data === 'undefined') {
if ("production" !== process.env.NODE_ENV) {
throw new Error("Cannot find mutation \"" + mutationPath + "\". Unable to update query list.");
} else {
return;
}
}
set(nextResult, listPath, [...list, data]);
cache.writeQuery(_extends({}, query, {
data: nextResult
}));
};
}