querying graphql with node

Viewed 5505

I am trying to query a graphQL endpoint but I can't figure out what I am doing wrong. How am I supposed to set up the graphQL object to pass over. If I am trying to pass

{
  name {
     age
  }
}

How should I be wrapping this to get the correct response from the server? The full code I am currently working with is below

var http = require('http')
var qs = require('querystring')

var options = {
    hostname: 'url',
    method: 'POST',
    path: '/query'
}

var req = http.request(options, function(res){
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
    res.on('end', function() {
        console.log('No more data in response.')
    })
})

var query = qs.stringify({data: {classes:{}}})


req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.write(query)
req.end()
3 Answers

You can do it like this.

payload = {
    "query": `{
        name {
            age
        }
    }`
}
JSON.stringify(payload)

The name "query" might be different in your case. Basically, you need to convert the JSON query to string. This is how I do it with the GitHub GraphQL API v4.

Here is the example using fetch. I think you don't need apollo client unless you really need it.

require('isomorphic-fetch');

fetch('https://api.example.com/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'authorization': `Bearer ${token}`,
      },
      body: JSON.stringify({ query: '{ name { age } }' }),
})

I've found that the easiest way to do this is by using the Apollo Client library @apollo/client. You should note however that this library unfortunately makes the assumption that you're using React, and there's no vanilla JS client, but you can still import the classes you need from core and avoid any React dependencies.

import {
    ApolloClient,
    InMemoryCache,
    HttpLink
} from "@apollo/client/core"
// Use cross-fetch for Node versions lower than 18.
import fetch from 'cross-fetch'

const client = new ApolloClient({
    link: new HttpLink({ uri, fetch }),
    cache: new InMemoryCache(),
    name: "my client",
    version: "1.0.0",
    assumeImmutableResults: true
})

const query = gql`
    query Query {
        hello
    }
`
const response = await client.query({ query })

Also note that there used to be a bug with old versions of @apollo/client/core having an unnecessary React dependency, I'm using "@apollo/client": "^3.6.5" and don't have that issue.

Related