Jay*_*ell 5 javascript typescript graphql graphql-js nestjs
在此处引用 NestJS 存储库中的 type-graphql 示例存储库,我想知道如何在查询的深处再创建两层。
目前它已设置为查询食谱,我能够添加另一个@ObjectType 类
@ObjectType()
export class Author {
@Field(type => Int)
id: number;
@Field({ nullable: true })
firstName?: string;
@Field({ nullable: true })
lastName?: string;
}
Run Code Online (Sandbox Code Playgroud)
并在 Recipe Resolver 中创建了一个 @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' });
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好(我还为 Author 创建了一个单独的解析器,但它不是我的基本查询,所以我没有包含它),使用这个 GraphQL 查询
{
recipe(id: "1") {
title,
author {
firstName
}
}
}
Run Code Online (Sandbox Code Playgroud)
此查询返回
{
"data": {
"recipe": {
"title": "1",
"author": {
"firstName": "john"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如它应该。我现在的问题是如何添加另一个级别?我试图创建一个“发布者”对象类型
@ObjectType()
export class Publisher {
@Field(type => Int)
id: number;
}
Run Code Online (Sandbox Code Playgroud)
但是,在 Author 和 Recipe 解析器中创建解析器或添加 ResolveProperty 的组合都无法使其工作。我应该把解析器代码放在哪里,这样当 GraphQL 解析 Author 对象时,它也会解析关联的发布者信息。
我的目标是得到它,以便查询,例如:
{
recipe(id: "1") {
title,
author {
firstName,
publisher: {
id
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
会回来
{
"data": {
"recipe": {
"title": "1",
"author": {
"firstName": "jay",
"publisher": {
id: 4
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
不确定我是否在考虑这个错误,但这似乎是我无法扩展的一个关键想法!谢谢你。
您基本上只需定义一个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!
}
Run Code Online (Sandbox Code Playgroud)
请注意,您需要创建自己的PublisherObjectType(使用各自的装饰器)并使其可用。
| 归档时间: |
|
| 查看次数: |
2885 次 |
| 最近记录: |