引用NestJS存储库here中的type-graphql示例存储库,我想知道如何在查询中再创建两层。
目前已设置为查询配方,我能够添加另一个@ObjectType类
@ObjectType()
export class Author {
@Field(type => Int)
id: number;
@Field({ nullable: true })
firstName?: string;
@Field({ nullable: true })
lastName?: string;
}
并在配方解析器中创建了一个@ResolveProperty:
@ResolveProperty('author', type => Author)
async getAuthor(@Parent() recipe) {
console.log('Resolver auth in recipe', recipe);
// This will be a database call, just mocking data for now.
return Promise.resolve({ id: 1, firstName: 'john', lastName: 'smith' });
}
使用此GraphQL查询,一切正常(我还为Author创建了一个单独的解析器,但它不是我的基本查询,因此不包含它)
{
recipe(id: "1") {
title,
author {
firstName
}
}
}
该查询返回
{
"data": {
"recipe": {
"title": "1",
"author": {
"firstName": "john"
}
}
}
}
正如它应该。我现在的问题是如何添加另一个级别?我试图创建一个“发布者” ObjectType
@ObjectType()
export class Publisher {
@Field(type => Int)
id: number;
}
但是,在Author和Recipe解析器中创建解析器或添加ResolveProperty并没有使其工作。我应该将解析器代码放在哪里,以便当GraphQL解析器使用Author对象时,它还将解析关联的发布者信息。
我的目标是得到它,以便查询如:
{
recipe(id: "1") {
title,
author {
firstName,
publisher: {
id
}
}
}
}
会回来
{
"data": {
"recipe": {
"title": "1",
"author": {
"firstName": "jay",
"publisher": {
id: 4
}
}
}
}
}
不知道我是否在考虑这个错误,但这似乎是一个关键想法,我想继续扩展下去!谢谢。
最佳答案
基本上,您只需要定义一个AuthorResolver
即可描述如何与Author
一起“工作”。在此AuthorResolver
中,您将拥有一个@ResolveProperty
装饰的方法来解析publisher
属性,如下所示:
// author.resolver.ts
@ResolveProperty('publisher', type => PublisherObjectType, {})
async resolvePublisher(@Parent() parent: AuthorEntity) {
return parent.getPublisher(); // this method would return your Publisher!
}
请注意,您需要创建自己的PublisherObjectType
(带有相应的装饰器)并使其可用。