Validate GraphQL-Ruby inputs without messing up your queries and mutations

Giovanni Benussi
1 min readSep 14, 2017

I used to validate inputs in GraphQL Ruby this way:

If you have to do many custom validations, your queries/mutations rapidly will begin to grow with code that isn’t closely related to it’s main purpose.

As an alternative, you could use a custom validator so we can change the code above to this:

If you want to have a validator that is called using Validators::Model.validate!(args), you need to create a custom class file in app/graphql/validators/model.rb with the following content:

This way, if you want to add more validations, you only have to add it to this new class instead of clutter your queries/mutations with validation code.

Also, if you want to go even further, you can create a new class to abstract the presence validation:

You can place this class in app/graphql/validators/graphql_validator.rb to allow GraphQL Ruby load it automatically. You can now replace your custom model validator with this code:

By using custom validators, you will have your code more organized, without too much clutter and you will know rapidly where to look when you need to add a custom validation to your queries and/or mutations!

--

--