Created
February 22, 2019 09:55
-
-
Save Akiyamka/72678919534bafdd6d9d89e4564237f3 to your computer and use it in GitHub Desktop.
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
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