3

我正在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 对象的问题。

4

2 回答 2

2

您的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); });

}
于 2018-08-19T17:43:56.407 回答
1

在这种情况下使用data.merchant解决了我的问题。但是上面建议的解决方案,即使用JSON.parse(...)可能不是最佳实践,因为如果 JSON 中没有对象,那么预期的响应可能如下:

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

而不是字段是null.

{
  "data": {
    "merchant": {
      "id": null // even though merchant is null in JSON, 
                 // I am getting a merchant object in response from GraphQL
    }
  }
}

我已经用工作代码更新了我的 GitHub: https ://github.com/vishrantgupta/graphql。

于 2018-08-20T00:47:11.640 回答