通过REST API运行GraphQL会返回空数据

时间:2017-01-20 11:40:37

标签: graphql graphql-js

我按照博文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

1 个答案:

答案 0 :(得分:0)

最后我找到了原因 - 这是语法,而不是返回的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
							}),				
    },
  }),
});