I am learning how to use NestJs with GraphQL but I am stuck with validations. I had a CreatePostInput (Dto)
with some validations using class-validator
library but none of the validations work when I use a Resolver
instead to a Controller
to get the data. below you'll find some parts of the code, there is also a repo:
// main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({transform: true}));
await app.listen(process.env.PORT ?? 4000);
}
bootstrap();
// posts.resolver.ts
@Resolver(Post)
export class PostsResolver {
constructor(private readonly todosService: PostsService) {}
@Mutation(() => Post)
async createPost(@Args("createPostInput") createPostInput: CreatePostInput) {
return this.todosService.create(createPostInput);
}
}
// post.entity.ts
@ObjectType()
export class Post {
@Field(() => Int)
id: number;
@Field(() => String)
title: string;
@Field(() => String, { nullable: true })
content?: string | null;
@Field(() => Boolean)
published: boolean
}
// create-post.input.ts
@InputType()
export class CreatePostInput {
@Field(() => String)
@IsString()
@IsNotEmpty()
title: string;
@Field(() => String, { nullable: true })
@IsOptional()
@IsString()
content?: string | null;
}
When I pass an invalid value to the CreatePostInput
using a controller (POST) I get the errors from the validation and the status code (400). However when I make the query with invalid data (for example pass int value to string property) using grapql I get the error from GraqphQL (GraphQLError) without neither the validation formatted error nor status code.
I have searched info on the internet, watched YouTube videos, and read blogs but I haven't figured out what I'm missing or if I am doing something wrong. I would appreciate your help.