Created
March 25, 2017 05:49
-
-
Save SachaG/4384c46fad13cda92afc8fd250413295 to your computer and use it in GitHub Desktop.
Apollo Query Reducer
This file contains hidden or 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
const CommentsPageWithData = graphql(CommentsPageQuery, { | |
props({ data }) { | |
// ... | |
}, | |
options({ params }) { | |
return { | |
reducer: (previousResults, action, variables) => { | |
let newResults = previousResults; | |
// check if a document belongs to the current query | |
const belongsToQuery = (documents) => { /* ... */ } | |
// check if a document already exists in a results object | |
const existsInResults = (results, document) => { /* ... */ } | |
// remove a document from a results object, used by edit and remove cases below | |
const removeFromResults = (results, document) => { /* ... */ } | |
// add document to a results object | |
const addToResults = (results, document) => { /* ... */ } | |
// reorder results | |
const reorderResults = (results) => => { /* ... */ } | |
switch (action.operationName) { | |
case "new": | |
// get new document | |
const newDocument = action.result.data["new"]; | |
// if new document belongs to current results, add it | |
if (belongsToQuery(newDocument)) { | |
newResults = addToResults(previousResults, newDocument); | |
newResults = reorderResults(newResults); | |
} | |
break; | |
case "edit": | |
// get edited document | |
const editedDocument = action.result.data[editMutationName]; | |
// see if it still belongs to the current results | |
if (belongsToQuery(previousResults, editedDocument)) { | |
// if document wasn't already in results, add it | |
if (!existsInResults(previousResults, editedDocument)) { | |
newResults = addToResults(previousResults, editedDocument); | |
} | |
// reorder results | |
newResults = reorderResults(newResults, options.sort); | |
} else { | |
// if edited doesn't belong to current list anymore, remove it | |
newResults = removeFromResults(previousResults, editedDocument); | |
} | |
break; | |
case "remove": | |
// get removed document | |
const removedDocument = action.result.data[removeMutationName]; | |
// remove it from results object | |
newResults = removeFromResults(previousResults, removedDocument); | |
break; | |
default: | |
// default case: just return previous results unchanged | |
return previousResults; | |
} | |
// copy over arrays explicitely to ensure new sort is taken into account | |
return { | |
[listResolverName]: [...newResults[listResolverName]], | |
[totalResolverName]: newResults[totalResolverName], | |
} | |
} | |
}; | |
}, | |
})(CommentsPage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment