paint-brush
JavaScript GraphQL client requests in Node and the browser using `graphql.js`by@hugo__df
3,125 reads
3,125 reads

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

by Hugo Di FrancescoSeptember 5th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

See the example live: <a href="https://codewithhugo.com/js-graphql-client-example/" target="_blank">https://codewithhugo.com/js-graphql-client-example/</a>.
featured image - JavaScript GraphQL client requests in Node and the browser using `graphql.js`
Hugo Di Francesco HackerNoon profile picture

Andrew Pons on Unsplash

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.

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};


















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

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>`;})}

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>

$ npm install --save-dev parcel

$ npx parcel index.html

Open http://localhost:1234.

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
















{pokemon(name: "Pikachu") {attacks {fast {nametypedamage}special {typedamagename}}}}

And click Try it. Which yields the following:

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.

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.

Originally published at codewithhugo.com on September 5, 2018.