首页 > 解决方案 > 带有 RESTful 的 GraphQL 返回空响应

问题描述

我正在GraphQLREST端点连接,我确认每当我调用http://localhost:3001/graphql它时它都会击中REST端点并且它正在JSON向服务器返回响应GraphQL,但是我从GraphQL服务器得到一个空响应,GUI如下所示:

{
  "data": {
    "merchant": {
      "id": null
    }
  }
}

查询(手动解码):

http://localhost:3001/graphql?query={
  merchant(id: 1) {
    id
  }
}

下面是我的GraphQLObjectType样子:

const MerchantType = new GraphQLObjectType({
  name: 'Merchant',
  description: 'Merchant details',
  fields : () => ({
    id : {
      type: GraphQLString // ,
      // resolve: merchant => merchant.id
    },
    email: {type: GraphQLString}, // same name as field in REST response, so resolver is not requested
    mobile: {type: GraphQLString}
  })
});


const QueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'The root of all... queries',
  fields: () => ({
    merchant: {
      type: merchant.MerchantType,
      args: {
        id: {type: new GraphQLNonNull(GraphQLID)},
      },
      resolve: (root, args) => rest.fetchResponseByURL(`merchant/${args.id}/`)
    },
  }),
});

来自端点的响应REST(我也尝试使用 JSON 中的单个对象而不是 JSON 数组):

[
  {
    "merchant": {
      "id": "1",
      "email": "a@b.com",
      "mobile": "1234567890"
    }
  }
]

REST调用使用node-fetch

function fetchResponseByURL(relativeURL) {

  return fetch(`${config.BASE_URL}${relativeURL}`, {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    }
  })
  .then(response => {
    if (response.ok) {
      return response.json();
    }
  })
  .catch(error => { console.log('request failed', error); });

}

const rest = {
  fetchResponseByURL
}

export default rest

GitHub:https
://github.com/vishrantgupta/graphql JSON端点(虚拟):https ://api.myjson.com/bins/8lwqk

编辑:添加node.js标签,可能是 promise 对象的问题。

标签: node.jsexpressgraphqlexpress-graphql

解决方案


您的fetchResponseByURL函数获取空字符串。

我认为主要问题是您使用错误的函数来获取您的 JSON 字符串,请尝试安装request-promise并使用它来获取您的 JSON 字符串。

https://github.com/request/request-promise#readme

就像是

var rp = require('request-promise');
function fetchResponseByURL(relativeURL) {
  return rp('https://api.myjson.com/bins/8lwqk')
    .then((html) => {
      const data = JSON.parse(html)
      return data.merchant
    })
    .catch((err) => console.error(err));
  // .catch(error => { console.log('request failed', error); });

}

推荐阅读