相互依赖的 graphQl 类型
interdependent graphQl types
我想设计一个 graphQl 模式,其中两种类型相互依赖。基本上我有一个数据库结构,其中:
User.hasOne(Search)
我希望能够像这样进行 graphQl 查询:
// note that 'me' has User type
// search has Search type
query{
me{
email,
search{
content,
user{
id
}
}
}
}
所以,你看到我们请求一个 User
,它的 Search
和拥有这个 Search
的 User
(好的,在这种情况下这根本没有用).
下面是 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
和 SearchType
之间的相互依赖,我得到以下错误:
User.search field type must be Output Type but got: function type() {
return _SearchType2.default;
}
有什么方法可以在 User
和 Search
之间实现这种相互依赖?
从这个页面 http://graphql.org/graphql-js/type/#graphqlobjecttype
看看 PersonType 是如何依赖自身的?
var PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => ({
name: { type: GraphQLString },
bestFriend: { type: PersonType },
})
});
您要找的是
fields: () => ({
...
})
我想设计一个 graphQl 模式,其中两种类型相互依赖。基本上我有一个数据库结构,其中:
User.hasOne(Search)
我希望能够像这样进行 graphQl 查询:
// note that 'me' has User type
// search has Search type
query{
me{
email,
search{
content,
user{
id
}
}
}
}
所以,你看到我们请求一个 User
,它的 Search
和拥有这个 Search
的 User
(好的,在这种情况下这根本没有用).
下面是 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
和 SearchType
之间的相互依赖,我得到以下错误:
User.search field type must be Output Type but got: function type() {
return _SearchType2.default;
}
有什么方法可以在 User
和 Search
之间实现这种相互依赖?
从这个页面 http://graphql.org/graphql-js/type/#graphqlobjecttype 看看 PersonType 是如何依赖自身的?
var PersonType = new GraphQLObjectType({
name: 'Person',
fields: () => ({
name: { type: GraphQLString },
bestFriend: { type: PersonType },
})
});
您要找的是
fields: () => ({
...
})