Skip to content

Instantly share code, notes, and snippets.

@conorhastings
Last active July 28, 2018 19:26
Show Gist options
  • Save conorhastings/700e12775383377e5f9ae7342caed42b to your computer and use it in GitHub Desktop.
Save conorhastings/700e12775383377e5f9ae7342caed42b to your computer and use it in GitHub Desktop.
import gql from 'graphql-tag';
import { pick } = 'lodash'
function routeql({ query = {}, params = [], method, apiPrefix = "" }) {
const ast = gql`
${query}
`;
if (
ast.definitions.length > 1 ||
ast.definitions[0].selectionSet.selections.length > 1
) {
throw new Error('nested definitions are currently not supported');
}
const def = ast.definitions[0];
const route = def.selectionSet.selections[0];
const routeName = route.name.value;
const fields = route.selectionSet.selections.map(field => field.name.value);
const reqType = method || def.operation === "query" ? "GET" : "POST";
const paramString = params.reduce(acc, param => `${acc}/${param}`, "/");
const queryStrying = Object.entries(query).reduce(
(qs, [key, value]) => `${qs}${qs.length === 1 ? "" : "&"}${key}=${value}`,
"?"
);
return fetch(`${apiPrefix}/${route}/${paramString}${queryString}`, {
method: reqType
})
.then(res => res.json())
.then(data => pick(data, fields));
}
routeql({
query: `
query {
document {
id
name
type
}
}
`,
params: ["1"],
apiPrefix: "/api/v1"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment