Last active
July 28, 2018 19:26
-
-
Save conorhastings/700e12775383377e5f9ae7342caed42b to your computer and use it in GitHub Desktop.
This file contains 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
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