Skip to content

Instantly share code, notes, and snippets.

@dannydenenberg
Created August 21, 2020 02:09
Show Gist options
  • Select an option

  • Save dannydenenberg/a2b5fa326ff2eab20e4711c38c511822 to your computer and use it in GitHub Desktop.

Select an option

Save dannydenenberg/a2b5fa326ff2eab20e4711c38c511822 to your computer and use it in GitHub Desktop.

Revisions

  1. dannydenenberg created this gist Aug 21, 2020.
    52 changes: 52 additions & 0 deletions graphql-client.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    import fetch from "node-fetch";

    /** EXAMPLE USAGE **/

    const client = new GraphqlClient('http://localhost:3000');
    client.query(HELLO).then(data => console.log(data));

    const HELLO = `
    {
    hello
    }
    `;



    /** CLIENT CODE **/
    class GraphqlClient {
    // server defaults to the current server
    constructor(server = "", graphqlRoute = "/graphql") {
    this.server = server;
    this.graphqlRoute = graphqlRoute;
    }

    // query: string, variables: {var1: 'a', var2: 'b'...}
    query(query, variables = {}) {
    return new Promise((resolve, reject) => {
    // uses node-fetch
    fetch(`${this.server}${this.graphqlRoute}`, {
    method: "POST",
    headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
    },
    body: JSON.stringify({
    query,
    variables,
    }),
    })
    .then((r) => r.json())
    .then((data) => resolve(data))
    .catch((err) => reject(err));
    });
    }

    mutate(mutation, variables) {
    return this.query(mutation, variables);
    }
    }