我有3个文件:authors.py
,posts.py
和schema.py
。
帖子只有一位作者,查询是在架构文件中构建的。
我正在尝试从Author
内部解析Post
,而未在Post
中声明解析器函数,因为Author
已经声明了自己的解析器函数。以下代码有效,但是我必须从resolve_author
类型内部引用Post
,但这似乎不正确。我认为石墨烯应将parent
参数直接传递给Author
,不是吗?
如果我没有为author
类型的Post
设置解析器,它只会返回null
。
schema.py
import graphene
from graphql_api import posts, authors
class Query(posts.Query, authors.Query):
pass
schema = graphene.Schema(query=Query)
authors.py
from graphene import ObjectType, String, Field
class Author(ObjectType):
id = ID()
name = String()
class Query(ObjectType):
author = Field(Author)
def resolve_author(parent, info):
return {
'id': '123',
'name': 'Grizzly Bear',
'avatar': '#984321'
}
posts.py
from graphene import ObjectType, String, Field
from graphql_api import authors
class Post(ObjectType):
content = String()
author = Field(authors.Author)
def resolve_author(parent, info):
# I'm doing like this and it works, but it seems wrong.
# I think Graphene should be able to use my resolver
# from the Author automatically...
return authors.Query.resolve_author(parent,
info, id=parent['authorId'])
class Query(ObjectType):
post = Field(Post)
def resolve_post(parent, info):
return {
'content': 'A title',
'authorId': '123',
}
答案 0 :(得分:0)
Query.resolve_author
不会被调用,因为它与Post
对象之间没有关系。
我建议类似的东西
from graphene import ObjectType, String, Field
from graphql_api import authors
class Post(ObjectType):
content = String()
author = Field(authors.Author)
def resolve_author(self, info):
# author_utils.get_author returns complete object that will be passed into Author's object resolvers (if some fields are missing)
# I suggest returning here an object from database so author resolver would extract another fields inside
# But it may be just an id that will be passed in Author resolvers as first arguments
return author_utils.get_author(post_id=self.id)
class Query(ObjectType):
post = Field(Post)
def resolve_post(parent, info):
# Here you shouldn't author_id as it's not defined in type
return {
'content': 'A title',
}
然后Author
(假设author_utils.get_author
仅返回一个id):
class Author(ObjectType):
id = ID()
name = String()
def resolve_id(id, info):
# root here is what resolve_author returned in post. Be careful, it also will be called if id is missing after Query.resolve_author
return id
def resolve_name(id, info):
# same as resolve_id
return utils.get_name_by_id(id)