JavaScript GraphQL client requests in Node and the browser using `graphql.js`

hugo__df

Hugo Di Francesco

Posted on September 5, 2018

JavaScript GraphQL client requests in Node and the browser using `graphql.js`

An example consuming a GraphQL API in JavaScript from Node and the browser using graphql.js

See the example live: https://codewithhugo.com/js-graphql-client-example/.

Full repo: https://github.com/HugoDF/js-graphql-client-example.

  • Fetching from Node
  • Fetching from the browser
  • GraphQL documentation tools

This was sent out on the Code with Hugo newsletter last Monday.
Subscribe to get the latest posts right in your inbox (before anyone else).

Fetching from Node

fetch.js:

const graphql = require('graphql.js');

const graph = graphql('https://graphql-pokemon.now.sh/');

const query = graph(`{
  pokemon(name: "Pikachu") {
    attacks {
      special {
        name
      }
    }
  }
}`);

if (require.main === module) {
  query().then(
    res => console.log(JSON.stringify(res, null, 2)),
    err => console.error(err)
  );
}

module.exports = {
  query
};
Enter fullscreen mode Exit fullscreen mode

$ node fetch.js
{
  "pokemon": {
    "attacks": {
      "special": [
        {
          "name": "Discharge"
        },
        {
          "name": "Thunder"
        },
        {
          "name": "Thunderbolt"
        }
      ]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Fetching from the browser

graphql.js is isomorphic, it’ll also run in the browser, we’ll use Parcel to stitch everything together.

By default we fetch using the query from fetch.js, then when the user clicks the Try it button we use the contents of the textarea.

This code wires up the fetch logic with some reading the query from the DOM and updating an output div on completion, client.js:

const { query, graph } =require('./fetch');

const $queryElement = document.querySelector('.query');
const $output = document.querySelector('.output');
const $submitButton = document.querySelector('button');

$submitButton.onclick = () => {
  const queryData = $queryElement.value;
  runQuery(graph(queryData))
}

runQuery(query);

function runQuery (query) {
  query().then(
    res => {
      $output.innerHTML = `<pre><code>${JSON.stringify(res, null, 2)}</code></pre>`;
    },
    err => {
      $output.innerHTML = `Error: <pre><code>${JSON.stringify(err, null, 2)}</code></pre>`;
    }
  )
}

Enter fullscreen mode Exit fullscreen mode

index.html:

<!doctype html>
<html class="no-js" lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>JavaScript GraphQL Client Example</title>
  <meta name="description" content="JavaScript GraphQL Client example">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont,
          'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell,
          'Open Sans', 'Helvetica Neue', sans-serif;
    }
  </style>
</head>

<body>
  <p>For full documentation see: <a href="https://graphql-pokemon.now.sh/">https://graphql-pokemon.now.sh/</a></p>
  <h2>Input: </h2>
  <textarea class="query" style="min-width: 285px; min-height: 150px">
{
  pokemon(name: "Pikachu") {
    attacks {
      special {
        name
      }
    }
  }
}
  </textarea>
  <button>Try it</button>
  <h2>Output: </h2>
  <div class="output"></div>
  <script src="./client.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode
$ npm install --save-dev parcel

$ npx parcel index.html
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:1234.

Sample GraphQL query result displayed in the browser

To test it out, we can change the textarea content to:

{
  pokemon(name: "Pikachu") {
    attacks {
      fast {
        name
        type
        damage
      }
      special {
        type
        damage
        name
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

And click Try it. Which yields the following:

new GraphQL query output in browser

GraphQL documentation tools

For the hosted GraphQL docs of the pokemon GraphQL API, see https://graphql-pokemon.now.sh/, it opens GraphiQL where you can explore the API, use CTRL + space to show field suggestions, and CMD + enter to expand all nested fields by default. You can also right-click on a field to explore its type etc.

GraphiQL for pokemon GraphQL API

More about GraphQL coming next week in the Code with Hugo newsletter so subscribe if you’re not already.

If you have any questions feel free to tweet at me @hugo__df.

Andrew Pons

💖 💪 🙅 🚩
hugo__df
Hugo Di Francesco

Posted on September 5, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related