【问题标题】:interdependent graphQl types相互依赖的graphQl类型
【发布时间】:2017-05-09 22:40:43
【问题描述】:

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

User.hasOne(Search)

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

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

所以,你看到我们请求了一个User,它的Search 和拥有这个SearchUser(好吧,在这种情况下这根本没有用)。

这是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 },
  },
});

不幸的是,这不起作用,我猜是由于UserTypeSearchType之间的相互依赖,我收到以下错误:

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

有什么方法可以实现UserSearch 之间的这种相互依赖关系?

【问题讨论】:

    标签: javascript graphql


    【解决方案1】:

    从此页面http://graphql.org/graphql-js/type/#graphqlobjecttype 看看 PersonType 是如何依赖自身的?

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

    你要找的东西是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2020-06-12
      • 1970-01-01
      相关资源
      最近更新 更多