DEV Community

Ian Fabs
Ian Fabs

Posted on • Edited on

3 2

I made a fetch-wrapper for making graphql api calls!

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay