NestJS 和 Graphql 突变:DTO 和 CreateInput

问题描述 投票:0回答:1

我想将活动添加到最喜欢的表中:

@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 应该只有 Activity 的 id,userId 将与当前的身份验证会话一起保存,如下代码所示:

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

我的 DTO 有活动并且

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

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

当我尝试生成类型时出现此错误:

错误0:无法查询类型“FavoriteDto”上的字段“activityId”。您指的是“活动”吗?

如何将 CreateFavoriteInput 与 DTO 匹配?

graphql nestjs dto
1个回答
0
投票

我认为你期望的数据和你返回的数据之间存在误解

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

这里的FavoriteDto是你从

mutation

返回的类型

因此您无法查询

activityId
,因为它在您的
CreateFavoriteInput
中而不是在
FavoriteDto

在您的客户端中,您只能查询

id
activity
(假设它是从您的突变返回的)。如果您返回
activityId
,则只需在FavoriteDto 中将
id
替换为
activityId

如果你想保持一致,你应该更换

  @Args('createFavoriteInput') createFavoriteDto: CreateFavoriteInput

  @Args('createFavoriteInput') createFavoriteInput: CreateFavoriteInput

这样就不会混淆DTO类型和输入类型了。

© www.soinside.com 2019 - 2024. All rights reserved.