Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Created February 22, 2019 09:55
Show Gist options
  • Save Akiyamka/72678919534bafdd6d9d89e4564237f3 to your computer and use it in GitHub Desktop.
Save Akiyamka/72678919534bafdd6d9d89e4564237f3 to your computer and use it in GitHub Desktop.
export function chainQueries(queries) {
const defaultOptions = { errorPolicy: 'all' };
const checkLoadingAndError = allData => allData.loading || allData.error;
const maybeFunction = (t, args) => typeof t === 'function' ? t(args) : t;
const findQueryName = query => query.definitions[0].selectionSet.selections[0].name.value;
const queryNamesBuffer = [];
const pipeline = queries.map((q, i)=> {
if (q.kind === 'Document') { // Not sure about this way for detect query
queryNamesBuffer.push(findQueryName(q));
return graphql(q, {
skip: allPrevData => {
return i === 0 ? false : checkLoadingAndError(allPrevData)
},
options: allPrevData => {
return {
...defaultOptions,
variables: allPrevData.data
}
},
});
};
queryNamesBuffer.push(findQueryName(q.query));
const getPrevData = data => queryNamesBuffer[i - 1] ? data[queryNamesBuffer[i - 1]] : data;
const props = {
skip: ({ data: allPrevData }) => {
return q.skip ? maybeFunction(q.skip, allPrevData) : checkLoadingAndError(allPrevData)
},
options: ({ data: allPrevData }) => ({
...defaultOptions,
variables: q.variables ? maybeFunction(q.variables, getPrevData(allPrevData)) : allPrevData
})
}
return graphql(q.query, props)
});
function readyCheck(children) {
return props => {
const { data: { loading, error, data } } = props
if (error) console.warn(error)
if (loading || error) return null;
return children(data);
}
}
pipeline.push(readyCheck);
return pipeline;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment