Argument and Input validation
Scalars
The standard way to ensure that inputs and arguments are correct, such as an email field that really contains a proper e-mail address, is to use custom scalars e.g. GraphQLEmail from graphql-custom-types. However, creating scalars for all single cases of data types (credit card number, base64, IP, URL) might be cumbersome.
That's why TypeGraphQL has built-in support for argument and input validation.
By default, we can use the class-validator library and easily declare the requirements for incoming data (e.g. a number is in the range 0-255 or a password that is longer than 8 characters) thanks to the awesomeness of decorators.
We can also use other libraries or our own custom solution, as described in custom validators section.
class-validator
How to use
First, we need to install the class-validator package:
npm install class-validator
Then we decorate the input/arguments class with the appropriate decorators from class-validator.
So we take this:
@InputType()
export class RecipeInput {
@Field()
title: string;
@Field({ nullable: true })
description?: string;
}
...and turn it into this:
import { MaxLength, Length } from "class-validator";
@InputType()
export class RecipeInput {
@Field()
@MaxLength(30)
title: string;
@Field({ nullable: true })
@Length(30, 255)
description?: string;
}
Then we need to enable the auto-validate feature (as it's disabled by default) by simply setting validate: true in buildSchema options, e.g.:
const schema = await buildSchema({
resolvers: [RecipeResolver],
validate: true, // Enable 'class-validator' integration
});
And that's it! 😉
TypeGraphQL will automatically validate our inputs and arguments based on the definitions:
@Resolver(of => Recipe)
export class RecipeResolver {
@Mutation(returns => Recipe)
async addRecipe(@Arg("input") recipeInput: RecipeInput): Promise<Recipe> {
// 100% sure that the input is correct
console.assert(recipeInput.title.length <= 30);
console.assert(recipeInput.description.length >= 30);
console.assert(recipeInput.description.length <= 255);
}
}
Of course, there are many more decorators we have access to, not just the simple @Length decorator used in the example above, so take a look at the class-validator documentation.
This feature is enabled by default. However, we can disable it if we must:
const schema = await buildSchema({
resolvers: [RecipeResolver]