带有RESTful的GraphQL返回空响应

时间:2018-08-19 02:04:56

标签: node.js express graphql express-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"
    }
  }
]

使用node-fetch

进行REST调用
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标签,可能是诺言对象的问题。

2 个答案:

答案 0 :(得分: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); });

}

答案 1 :(得分: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