Reputation: 233
I want to call to API, get json data and set it to resolvers Query in Graphql. So far I managed to working Graphql server and get call to API. This is my code so far
//resolvers.js
//var fetch = require('node-fetch');
var request = require("request");
var options = { method: 'GET',
url: 'http://mydomain.con/index.php/rest/V1/products/24-MB01',
headers:
{ 'postman-token': 'mytoken',
'cache-control': 'no-cache',
'content-type': 'application/json',
authorization: 'Bearer mytoken' } };
const links = request(options, function (error, response, body) {
if (error) throw new Error(error);
//body = json data
//console.log(body);
});
module.exports = {
Query: {
//set data to Query
allLinks: () => links,
},
};
I dont know how to set the body parameter which contain json data to Query. I have also same data on "http://localhost/src/apicall.php" but this is not working with node-fetch (or Im making mistakes). Api is from magento2.
Upvotes: 1
Views: 1542
Reputation: 5569
You were close !
What you are doing right now is sending the links
request right when your application starts. You don't want that ; you want to send the request when the allLinks
field is requested in GraphQL.
So what you need is to have in the allLinks
field a function making the request to your API, and returning the response.
If you return a Promise within the allLinks
field, it will wait upon completion to use the returned value as an answer.
So, putting it all together:
...
const getAllLinks = () => {
return new Promise((resolve, reject) => {
request(options, function (error, response, body) {
if (error) reject(error);
else resolve(body);
});
});
};
module.exports = {
Query: {
//set data to Query
allLinks: getAllLinks,
},
};
Upvotes: 1