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

标签 javascript php magento2 graphql

我想调用 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 数据的 body 参数设置为 Query。我在“http://localhost/src/apicall.php”上也有相同的数据,但这不适用于节点获取(或者我犯了错误)。 Api 来自 magento2。

最佳答案

你很接近!

您现在正在做的是在您的应用程序启动时立即发送 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,
  },
};

关于javascript - 如何将 API 数据提取到 Graphql 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303419/

相关文章:

javascript - 使用使用 inboxsdk 创建的自定义按钮发送邮件?

javascript - 从 Node.js 加密库获得奇怪的结果

php - 使用 PHP 更新 MySQL 数据库

magento2 - Magento 2 : How to get multiple selection attibute as list on list. phtml

magento - 在 phtml 文件中获取 magento 2 自定义变量

javascript - 如何通过单击按钮删除多行

javascript - 在应用程序中收听 chrome 扩展安装

php - 是否可以检测视口(viewport)宽度并在 jquery 中写入 mysql,然后在不重新加载页面的情况下在 php 中检索宽度

javascript - 从 mysql 数据库查询的名称不会显示在 jQuery Mobile 远程自动完成 ListView 中

rest - Magento 2 REST API 客户自定义属性