相互依赖的graphQl类型

时间:2016-12-24 15:59:57

标签: javascript graphql

我想设计一个graphQl模式,其中两种类型是相互依赖的。基本上我有一个数据库结构,其中:

User.hasOne(Search)

我希望能够像这样进行graphQl查询:

// note that 'me' has User type
// search has Search type
query{
  me{
    email,
    search{
      content,
      user{
       id
      }
    }
  }
}

因此,您看到我们请求User,其SearchUser拥有此Search(在这种情况下,这根本没有用)。

以下是UserType

的定义
import {
  GraphQLObjectType as ObjectType,
  GraphQLID as ID,
  GraphQLString as StringType,
  GraphQLNonNull as NonNull,
  GraphQLInt as IntType,
} from 'graphql';

const UserType = new ObjectType({
  name: 'User',
  fields: {
    id: { type: new NonNull(ID) },
    username: { type: StringType },
    search: {
      type: SearchType,
      resolve(user){
        return user.getSearch();
      }
    },
  },
});

以下是我对SearchType

的定义
const SearchType = new ObjectType({
  name: 'Search',
  fields: {
    id: { type: new NonNull(ID) },
    user: {
      type: UserType,
      resolve(search){
        return search.getUser();
      }
    },
    content: { type: StringType },
  },
});

不幸的是,这不起作用,我想由于UserType ans SearchType之间的相互依赖,我得到以下错误:

User.search field type must be Output Type but got: function type() {
  return _SearchType2.default;
}

我有没有办法在UserSearch之间实现这种相互依赖?

1 个答案:

答案 0 :(得分:3)

从此页面http://graphql.org/graphql-js/type/#graphqlobjecttype 了解PersonType如何依赖于自身?

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => ({
    name: { type: GraphQLString },
    bestFriend: { type: PersonType },
  })
});

你要找的东西是

fields: () => ({
...
})