3

I recently implemented a schema and some resolvers for my Express server. I tested them successfully through /graphql and now I would like to call the queries I implemented when accessing from a REST API, like so:

//[...]
//schema and root correctly implemented and working
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

//I start the server
app.listen(port, () => {
  console.log('We are live on ' + port);
});

//one of many GET handlers
app.get("/mdc/all/:param", function(req, res) {
    //call one of the (parametrized) queries here
    //respond with the JSON result
});

How can I call the queries I defined with GraphQL inside my GET handlers? How do I pass parameters to them?

Thank you!

3
  • What do you want to return from that route? Commented Oct 16, 2018 at 9:52
  • Right now nothing, I would like to return some JSON containing the result of the query and use AXAJ to retrieve it from the frontend. Commented Oct 16, 2018 at 9:59
  • I ended up using the Apollo Client lib for this. Here's how. stackoverflow.com/a/72534090/4124574 Commented Jun 7, 2022 at 16:00

2 Answers 2

8

Basically you can just use http post method to fetch the data from a GraphQL API, but here very nice solution using node-fetch , to install it:

npm install node-fetch --save

and the code to use it is:

const fetch = require('node-fetch');

const accessToken = 'your_access_token_from_github';
const query = `
  query {
    repository(owner:"isaacs", name:"github") {
      issues(states:CLOSED) {
        totalCount
      }
    }
  }`;

fetch('https://api.github.com/graphql', {
  method: 'POST',
  body: JSON.stringify({query}),
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
}).then(res => res.text())
  .then(body => console.log(body)) // {"data":{"repository":{"issues":{"totalCount":247}}}}
  .catch(error => console.error(error));

this solution was taken from here

Sign up to request clarification or add additional context in comments.

Comments

3

You can use graphql-request.

import { request, GraphQLClient } from 'graphql-request'

// Run GraphQL queries/mutations using a static function
request(endpoint, query, variables).then((data) => console.log(data))

// ... or create a GraphQL client instance to send requests
const client = new GraphQLClient(endpoint, { headers: {} })
client.request(query, variables).then((data) => console.log(data))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.