The other day, I was playing around with GraphQL queries for a side-project that I'm building, when I realized that eventually - I'm gonna need to make calls to that API on the client-side. My first instinct was to look around for a way to do it using fetch, because I love the fetch API. However the way to do it using fetch is kinda gross, if I'm being honest. The first answer I found on stack overflow, showed it like this:
note that, for the examples, an example API that I created is used
fetch('https://csb-xpwq1o2824-xravvsjkul.now.sh/', {
method: "POST",
body: JSON.stringify({query: "query {items{title}}"})
})
Now, that's pretty nasty-looking. You could make it better with some variables, maybe a template string, something like this:
const url = "https://csb-xpwq1o2824-xravvsjkul.now.sh/";
const query = {
query: `
query{
items{
title
}
}
`
}
const body = JSON.stringify(query);
fetch(url, {
method: "POST",
body
})
Now while that may look satisfying, it didn't feel like a healthy-enough balance between the feel of fetch, and graphql. So I created a function that did just that for me. I realized how useful this could be to other developers, so I wrapped it up in an npm module, and published it. I call it jraph
, and it works like this and thanks to a comment from @qm3ster
, it now works like this:
import { jraph } from "jraph";
let jql = jraph("https://csb-xpwq1o2824-xravvsjkul.now.sh/");
(async () => {
let result = await jql`{
items{
title
info
}
}`
console.log(result)
})();
If you like it, you can check it out on npm, here!
Have a great day guys!
Top comments (0)