How to use nest js resolvefield and dataloader in nestjs/graphql?

1.2k Views Asked by At

I am facing two problems in using ResolveFeild decorator.

Here is my Category Entity-

@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;
}

I have one field subCategory. Subcategory entity is-

@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;
}

Then I run one query for returning Category.

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

//Resolver field for Category query

@ResolveField('subcategory', () => [Subcategory])
getSubCategory(
        @Parent() category: Category,
    ) {
    console.log(category)
}

In Console we can see-

{
  _id: new ObjectId("62a1b6bf182e9775f15f8433"),
  name: 'Shirts',
  description: 'This is computer descriptions',
  subCategory: [
    new ObjectId("62a21d65df7751587e09d163"),
    new ObjectId("62a21d52df7751587e09d15e")
  ],
  createdAt: 2022-06-09T09:00:47.607Z,
  updatedAt: 2022-06-10T12:43:28.158Z,
  __v: 0
}
{
  _id: new ObjectId("62a355c4cd532cce21b0a3d2"),
  name: 'Computer',
  description: 'Shirt is a category description!',
  subCategory: [],
  createdAt: 2022-06-10T14:31:32.634Z,
  updatedAt: 2022-06-10T14:31:32.634Z,
  __v: 0
}

Then how can I send this subCategory to category service?

I try it in this way-

const { subCategory } = category;
return this.categoryService.subCategoryBatch(subCategory)

and CategoryService-

async subCategoryBatch(subCategory: //What will be type?) {

}

can anyone help me or give any example code. And I also want to use dataloader in this project. Can anyone help me?

this is my project code- https://github.com/siamahnaf198/ebuy-back

Please help me and give just one example with dataloader and ResolveField dataloader working.

0

There are 0 best solutions below