简体   繁体   中英

Is it possible to maintain flat input structure with nestjs/graphql Args?

I have a simple query:

@Query(() => ProfileOutput)
async profile(@Args('id') id: string) {
  return await this.profileFacade.findProfileById(input.id);
}

The problem is that I want to apply @IsMongoId() from class-validator for the id here. I do not want to create new @InputType here, because I do not want to change API specification. Is there a way to apply validator like @IsMongoId here without the need to change query definition for frontend?

For anyone seeking an answer I found a feature called dedicated argument class . Instead of creating new input type as I thought like this:

@InputType()
export class MongoIdBaseInput {
  @IsMongoId()
  @Field()
  id: string;
}

@Query(() => ProfileOutput)
async profile(@Args('data') input: MongoIdBaseInput) {
  return await this.profileFacade.findProfileById(input.id);
}

We can define it almost the same, but annotate input with ArgsType it will maintain flat structure of args for us:

@ArgsType()
export class MongoIdBaseInput {
  @IsMongoId()
  @Field()
  id: string;
}

@Query(() => ProfileOutput)
async profile(@Args() input: MongoIdBaseInput) {
  return await this.profileFacade.findProfileById(input.id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM