【问题标题】:Getting data from API inside a graphQL resolver deployed on Azure node.js function从部署在 Azure node.js 函数上的 graphQL 解析器中的 API 获取数据
【发布时间】:2019-02-18 11:57:58
【问题描述】:

我正在尝试使用 Azure 函数在 node.js 平台上部署 GraphQL 服务器。我已经能够部署一个基本的hello world 应用程序。
但是,我需要从解析器中的后端 API 获取数据。我无法让 fetchrequest 包在 Azure 函数中工作。
以下是我的代码:

var { graphql, buildSchema } = require('graphql');  
var fetch = require('node-fetch');
var request = require('request');

var schema = buildSchema(`
  type Query {
    myObject: MyObject
  }

  type MyObject { 
   someId (data: String) : String
  }
`);

var root = { 
  myObject: () => {
     return { 
        someId: (args) => {
            // Code enters till this point. 
            // I can see context.info messages from here. 
            // return "hello";  <--- This works perfectly fine. 
            return request('http://example.com', function (error, response, body) {
                    // -----> Code never enters here.
                    return body;
                });                   
          }
       }   
   }
};

module.exports = function (context, req) {
     context.log('JavaScript HTTP trigger function processed a request.');
     graphql(schema, req.body, root)
        .then(response => {
           context.res = {
               body: JSON.strigify(response)
          };

    context.done();
 });
};

我尝试过使用fetchrequest 模块。但是对于他们两个,我看到了相同的行为 - 响应永远不会返回。请求最终会在 5 分钟后超时。如果我选择返回一些虚拟值而不是fetchrequest,我会看到响应正确返回到查询。使用fetch,我看不到then 块或catch 块正在执行。

注意:我在请求 URI 中尝试了 httphttps URL,但它们似乎都没有返回任何数据。

是我实现 fetch/request 的方式有问题,还是一般 Azure 函数有问题?

【问题讨论】:

  • 你看过这篇文章了吗? stackoverflow.com/questions/43123969/…
  • ^ 1. 这都是静态数据,可以正常工作。我需要从 API 获取数据。 2. 这使用了 Apollo-graphQL。我正在使用香草 graphQL

标签: azure graphql azure-functions graphql-js


【解决方案1】:

回答我自己的问题: 似乎 node-fetch 和 request 实际上并没有返回承诺。将 request 包裹在 Promise 周围似乎可以解决问题。类似于this answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2020-11-19
    • 2019-03-31
    • 2019-03-28
    • 2019-02-03
    • 2018-09-01
    • 2021-11-08
    相关资源
    最近更新 更多