我想调用API,获取json数据并将其设置为解析器Graphql中的Query。到目前为止,我设法使用Graphql服务器并调用API。到目前为止,这是我的代码
//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,
},
};
我不知道如何将包含json数据的body参数设置为Query。我在“http://localhost/src/apicall.php”上也有相同的数据,但这不适用于node-fetch(或我犯错误)。 Api来自magento2。
答案 0 :(得分:1)
你很亲密!
您现在正在做的是在您的应用程序启动时立即发送links
请求。你不想要那个;您希望在GraphQL中请求allLinks
字段时发送请求。
所以你需要的是在allLinks
字段中有一个函数向你的API发出请求,然后返回响应。
如果您在allLinks
字段中返回Promise,它将在完成后等待使用返回的值作为答案。
所以,把它们放在一起:
...
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,
},
};