Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question]: Implementing input validation across the entire schema #4937

Closed
alisaifee opened this issue Apr 28, 2024 · 2 comments
Closed

[Question]: Implementing input validation across the entire schema #4937

alisaifee opened this issue Apr 28, 2024 · 2 comments

Comments

@alisaifee
Copy link

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.

@alisaifee alisaifee changed the title [Question]: Implementing input variable validation across the entire schema [Question]: Implementing input validation across the entire schema Apr 28, 2024
@rmosolgo
Copy link
Owner

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?

@alisaifee
Copy link
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants