rmosolgo/graphql-ruby

[Question]: Implementing input validation across the entire schema

alisaifee opened this issue · 2 comments

Description

Apologies if this is covered in the documentation already - but I'm trying to find the right entry point to implement a general input validation (for example to reject any input variables that contain potentially unsafe characters in the associated values). I couldn't reason creating a Plugin or using a custom Rule for the StaticValidation flows for this purpose and am wondering if there is any recommendation for such a use case.

Hey! Great question. I'd suggest creating a custom String scalar, for example:

# app/graphql/types/ascii_string.rb
class Types::AsciiString < GraphQL::Types::String 
  description "An ASCII-only string"
  def coerce_input(input, ctx)
    if input.ascii_only? 
      super # this is valid input 
    else 
      raise GraphQL::ExecutionError, "Invalid AsciiString input: #{input.inspect}, remove non-ascii characters and try again." 
    end 
  end 
end 

Then, use that string for any arguments that should reject non-ascii characters:

field :create_new_user, Types::User do 
  argument :login, AsciiString
end 

That way, those arguments will use AsciiString's input validation. As a bonus, the schema's generated documentation will inform clients of the special requirements of that string, since it's an AsciiString, not a plain String. (If your validation isn't .ascii_only?, then use your validation code there instead.)

What do you think of that approach?

Thank you for the prompt reply @rmosolgo. This is definitely an approach I can work with and having the explicit scalar lending to better documentation of the expectation is a big bonus!