【问题标题】:Running GraphQL over REST API returns null data [duplicate]通过 REST API 运行 GraphQL 返回空数据 [重复]
【发布时间】:2017-06-05 09:28:12
【问题描述】:

我按照博文http://graphql.org/blog/rest-api-graphql-wrapper/ 中的说明浏览了这个博客 在我自己的 REST API 上创建一个 graphQL 端点。如果我在控制台中记录调用,我可以看到生成了正确的响应,但 GraphiQL IDE 中的数据始终为 NULL。可能是什么原因?

这是我的代码:

import {
	GraphQLSchema,
	GraphQLObjectType,
	GraphQLString,
} from 'graphql'

import fetch from 'node-fetch'

const BASE_URL = 'http://localhost/my.test.web/api/v1/customer/91/reservation'

const ReservationType = new  GraphQLObjectType({
	name: 'Reservation',
	description: 'This is reservation details',
	
	
	fields: () => ({
		id: {type: GraphQLString},
		confirmationNumber: {
			type: GraphQLString,
			resolve: (reservation) => reservation.confirmationNumber
		},
		status: {
			type: GraphQLString,
			resolve: (reservation) => reservation.status
		}
		
	})
});


const QueryType = new GraphQLObjectType(
{
	name: "query",
	description: "This is query by Id",
	
	fields: () => ({
			reservation: {
				type: ReservationType,
				args: {
					id: {type: GraphQLString}
				},
				resolve: (root, args) => {
					var url = BASE_URL+ '/' + args.id;
					console.log(url);
					var options = {
						headers: {
						'Accept': 'application/json',
						'Accept-Language':'en-US'
						}
					};					
					fetch(url,options)
					  .then(function(res) {
						  return res.json();
					  }).then(function(json) {
						  console.log(json);
						  return json;
					  });
					}
			}
		}
	)
});

export default new GraphQLSchema(
		{
			query: QueryType,
		}
	)

当我使用 graphiQL 和 express 运行它时,我可以看到这部分代码正确生成了日志 -

.then(function(json) {
                          console.log(json);
                          return json;
                      }

但在 GraphiQL UI 中,数据为空 GraphiQL IDE query screenshot

【问题讨论】:

  • 在日志语句中,我可以看到 API 返回的正确 JSON,但在 GraphiQL UI 中为空

标签: graphql graphql-js


【解决方案1】:

最后我找到了原因 - 这是语法而不是返回的 JSON。请注意每个块末尾的“,”,并且还删除了解析周围的包装:

QueryType 应该定义如下,它就像一个魅力

const QueryType = new GraphQLObjectType({
  name: "query",
  description: "This is person query by Id",
  fields: () => ({
    person: {
      type: PersonType,
      args: {
        id: { type: GraphQLString },
      },
      resolve: (root, args) => 				
					fetch(BASE_URL +'/people/' +args.id)
						.then(function(res) {
						  return res.json()
						})
							.then(function(json) {
							  console.log(json)
							  return json
							}),				
    },
  }),
});

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 2021-08-26
    • 2022-11-11
    • 2019-06-12
    • 2017-07-13
    • 2017-10-28
    • 2021-05-21
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多