Last active
March 3, 2017 16:19
-
-
Save reu/636f54901622f2b1576dfb8943275e96 to your computer and use it in GitHub Desktop.
Farfetch GraphQL fragments plugin
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 graphQLFragments = (fragments = {}) => req => { | |
const uniq = list => list.filter(value => list.indexOf(value) == list.lastIndexOf(value)); | |
const hasFragment = graphQL => graphQL.match(/\.{3}\s*([A-Za-z0-9\_]+)/g) != null; | |
const findFragments = graphQL => | |
graphQL | |
.match(/\.{3}\s*([A-Za-z0-9\_]+)/g) | |
.map(fragment => fragment.trim().replace(/^\.{3}/, "")) | |
.filter(fragment => fragment.match(/\s+on\s+/) == null) | |
.map(fragment => { | |
if (fragment in fragments) { | |
return hasFragment(fragments[fragment]) ? | |
[...findFragments(fragments[fragment]), fragment] : | |
[fragment]; | |
} else { | |
throw new Error(`GraphQL: Fragment ${fragment} not found.`); | |
} | |
}) | |
.reduce((all, current) => [current, ...all]); | |
const appendedFragments = uniq(findFragments(req.body.query)) | |
.map(fragment => `fragment ${fragment} on ${fragments[fragment]}`) | |
.join(""); | |
return { | |
...req, | |
body: { | |
...req.body, | |
query: req.body.query + appendedFragments, | |
}, | |
}; | |
}; |
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 graphAPI = farfetch | |
.post("http://api.graph.ql") | |
.set("Content-Type", "application/json") | |
.use(graphQLFragments({ | |
user: "User { id, name, posts { ...post } }", | |
post: "Post { id, body }", | |
})) | |
.use(req => ({ ...req, body: JSON.stringify(req.body) })) | |
.use((req, execute) => execute(req).then(res => res.json())); | |
const graph = (query, variables = {}) => graphAPI.send({ query, variables }); | |
const user = graph("query user($userId: ID!) { findUser(id: $userId) { ...user } }", { userId: "10" }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment