Skip to content

Instantly share code, notes, and snippets.

@reu reu/farfetch-graphql.js
Last active Mar 3, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.