NestJS and Graphql mutation: DTO and CreateInput

32 views Asked by At

I want to add an activity to a favorite table:

@Mutation(() => FavoriteDto)
@UseGuards(AuthGuard)
async createFavorite(
  @Context() context: any,
  @Args('createFavoriteInput') createFavoriteDto: CreateFavoriteInput,
): Promise<FavoriteDto> {
  const favorite = await this.favoriteService.create(
    context.user!.id,
    createFavoriteDto,
  );

  return this.favoriteMapper.convert(favorite);
}

CreateFavoriteInput should only have the id of the activity, the userId will be save with the current auth session like the following code bellow:

@InputType()
export class CreateFavoriteInput {
  @Field()
  @IsNotEmpty()
  @IsMongoId()
  activityId!: string;
}

My DTO has the activity and

@ObjectType()
export class FavoriteDto {
  @Field()
  id!: string;

  @Field(() => ActivityDto)
  activity!: ActivityDto;
}

When I tried to generate types I have this error:

Error 0: Cannot query field "activityId" on type "FavoriteDto". Did you mean "activity"?

How can I match my CreateFavoriteInput with my DTO ?

1

There are 1 answers

2
J.dev On

I think there is a misunderstanding between the data you expect and the data you return

@Mutation(() => FavoriteDto) // return type

Here FavoriteDto is the type you return from your mutation

So you can't query activityId as it's in your CreateFavoriteInput and not in FavoriteDto

In your client you can only query id and activity (assuming it's returned from your mutation). If you return an activityId you just have to replace id with activityId in FavoriteDto.

Also if you want to be consistent you should replace

  @Args('createFavoriteInput') createFavoriteDto: CreateFavoriteInput

with

  @Args('createFavoriteInput') createFavoriteInput: CreateFavoriteInput

So that it won't be confusing between DTO types and input types.