How to use nestjs @ResolveField Decorator Properly?

2.2k views Asked by At

I am creating one nestjs graphql api. I write all function correctly. But when I need to add @ResolveField into @Resolver Decorator, I am facing one problem. Can any tell me when I need two @ResolveField in one @Resolver, then How can I add it?

Here is Category Entity-(category.entity.ts)

@ObjectType()
export class Category {
    @Field(() => ID, { nullable: false })
    id: ObjectId;
    @Field(() => String, { nullable: false })
    name: string;
    @Field(() => String, { nullable: true })
    description: string;
    @Field(() => [Subcategory], { nullable: true })
    subCategory: Subcategory[];
    @Field(() => Date, { nullable: false })
    createdAt: DateScalar;
    @Field(() => Date, { nullable: false })
    updatedAt: DateScalar;
}

And Here is Subcategory Entity (sub-category.entity.ts)-

@ObjectType()
export class Subcategory {
    @Field(() => ID, { nullable: false })
    id: ObjectId;
    @Field(() => String, { nullable: false })
    name: string;
    @Field(() => Category, { nullable: false })
    category: Category;
    @Field(() => Date, { nullable: false })
    createdAt: DateScalar;
    @Field(() => Date, { nullable: false })
    updatedAt: DateScalar;
}

And This is Resolver (category.resolver.ts)-

@Resolver()
export class CategoryResolver {
    //Constructor
    constructor(private readonly categoryService: CategoryService) { }

    //Get All Category
    @Query(() => [Category], { name: "getCategories" })
    categories() {
        return this.categoryService.categories()
    }

    //Get All Sub Category
    @Query(() => [Subcategory], { name: "getSubCategories" })
    subCategories() {
        return this.categoryService.subCategories();
    }
    
    //Resolve Field

    //For Category
    @ResolveField("subCategory", () => [Subcategory])
    batchSubCategory(
        @Parent() category: Category
    ) {
        console.log(category);
    }
    //For Subcategory
    @ResolveField("category", () => Category)
    batchCategory(
        @Parent() subCategory: Subcategory
    ) {
        console.log(subCategory)
    }
}

Here you can see two @ResolveField Decorator. For working This I need to add Entity in @Resolver decorator, like-

@Resolver(Category)

or

@Resolver(Subcategory)

When I give Category then One ResolveField work perfectly, other is not working. Again When I give Subcategory then the other is working perfectly, but first one is not working. But When I give together then it gives me error-

@Resolver(Category, Subcategory)

Please help me. I need it Please help me. I can't solve it for 3 days. I search for the same things over internet but not finding any solutions.

0

There are 0 answers