如何将 API 数据提取到 Graphql 模式

How to fetch API data to Graphql schema

我想调用 API,获取 json 数据并将其设置为 Graphql 中的解析器查询。到目前为止,我设法运行 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 数据的正文参数设置为查询。我在“http://localhost/src/apicall.php”上也有相同的数据,但这不适用于节点获取(或者我犯了错误)。 Api 来自 magento2。

你很接近!

您现在正在做的是在您的应用程序启动时立即发送 links 请求。你不想要那个;您想在 GraphQL 中请求 allLinks 字段时发送请求。

因此,您需要在 allLinks 字段中包含一个向您的 API 发出请求并 return 响应的函数。

如果您 return allLinks 字段中的 Promise,它将等待完成后使用 returned 值作为答案。

所以,把它们放在一起:

...

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,
  },
};