Input validation
See original GitHub issueHi,
Currently the input of mutations is only validated by type. I.e. if I use setCustomerForOrder
it will report if any of the values is not defined or not a String
, but providing an empty string for any of the fields is accepted.
Also, for the emailAddress
field, a non-email string is also accepted.
I did a quick search and it seems that class-validator
is used with TypeORM for input validations:
https://github.com/typeorm/typeorm/blob/master/docs/validation.md
The resulting database error when inserting non-valid data could be wrapped in a ValidationError
result such that the frontend also knows what went wrong.
I also noticed that the customer service does a manual check for existing email addresses. Isn’t it easier to insert the new customer and check for a unique conflict error by adding the @Unique() decorator?
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (6 by maintainers)
Top GitHub Comments
I agree that validation would be useful beyond the basic type checking of GraphQL. I’d like to explore the options available for this. The class-validator lib looks like a good bet. Might also be useful to make the validations customizable to some degree, so that validations can be specified/modified by the user. Maybe the non-decorator method would allow us to abstract this into a friendly extensible API.
See this comment for an explanation of why we don’t add a unique constraint on that.
With soft-deletes it indeed makes sense to avoid the Unique constraint.
I think the validation should be split between the database level and the business-logic level. I.e. an email field in the database is required to be a valid email address (name@domain.ext), but on the business-logic level you might only want users with a ‘.com’ address to be able to order. .com only addresses is not a data validity concern so it should not be handled at the database level. However, there should be some protection at the database level to avoid inserting non-valid data (e.g. user@@domain.com is not valid).
A default validator for validation at the database level which can be extended with business logic would indeed be the ideal solution. It looks like NestJS normally uses the ValidationPipe, but perhaps a custom Pipe can be implemented.