Reputation: 21352
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!
Upvotes: 3
Views: 8877
Reputation: 1032
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))
Upvotes: 3
Reputation: 446
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
Upvotes: 8