【问题标题】:How to fetch API data to Graphql schema如何将 API 数据提取到 Graphql 架构
【发布时间】:2018-04-28 10:37:25
【问题描述】:

我想调用 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”上也有相同的数据,但这不适用于 node-fetch(或者我犯了错误)。 api来自magento2。

【问题讨论】:

    标签: javascript php magento2 graphql


    【解决方案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,
      },
    };
    

    【讨论】:

    • 对我有意义,但在 Graphql 中运行脚本后出现错误“错误:预期可迭代,但未找到字段 Query.allLinks。” .也许现在问题已经解决了?我的意思是它看起来像这样:{“id”:1,“sku”:“24-MB01”,“name”:“Joust Duffle Bag”等}而不是那样{id:1,sku:“24- MB01”,名称:“Joust Duffle Bag”等}
    • 这意味着 GraphQL 期待一个类似数组的对象,但您没有返回一个。您正在返回一个对象,但您确实将您的类型定义为[MyType],对吧?
    • 我的架构:const typeDefs = ` type Link { id: ID! sku:字符串! } 类型查询 { allLinks: [链接!]! } `; Schema 必须包含 json 数据中的所有字段?
    • 您将字段allLinks 定义为[Link!]!,这意味着您必须返回一组链接,而不是单个链接。尝试做resolve([body]),例如目的
    • 取得进展,现在“错误:无法为不可为空的字段 Link.id 返回 null。”
    猜你喜欢
    • 2020-09-05
    • 2022-08-20
    • 1970-01-01
    • 2020-02-26
    • 2019-05-11
    • 2018-12-07
    • 2022-07-03
    • 2010-10-16
    相关资源
    最近更新 更多