Skip to content

Instantly share code, notes, and snippets.

@reu
Last active March 3, 2017 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reu/636f54901622f2b1576dfb8943275e96 to your computer and use it in GitHub Desktop.
Save reu/636f54901622f2b1576dfb8943275e96 to your computer and use it in GitHub Desktop.
Farfetch GraphQL fragments plugin
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,
},
};
};
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