Using custom validators #3941
-
In a rails app, I am writing a mutation that will use a custom validation to validate the format of ISO 8601 duration strings Code looks something like this app/graphql/app_schema.rb class AppSchema < GraphQL::Schema
mutation(Types::MutationType)
query(Types::QueryType)
end app/graphql/types/mutation_type.rb module Types
class MutationType < Types::BaseObject
field :create_resource, mutation: Mutations::CreateResource do
end
end
end app/graphql/mutations/create_resource.rb module Mutations
class CreateResource < BaseMutation
argument :duration, String, required: false, validates: { iso_8601_duration: {} }
end
end My custom validation code looks something like this class ISO8601DurationValidator < GraphQL::Schema::Validator
def validate(_object, _context, value)
ActiveSupport::Duration.parse(value)
rescue ActiveSupport::Duration::ISO8601Parser::ParsingError => e
e.message
end
end
GraphQL::Schema::Validator.install(:iso_8601_duration, ISO8601DurationValidator) My question is, where in the file structure of a typical rails application should this custom validator code go? I originally put the class above my
To avoid this error when i boot rails in production mode, i have to move the validator into my |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
It can go anywhere, as long as it follows Rails project structure conventions (https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#project-structure). For example:
There's no convention with GraphQL-Ruby, so any of those should work fine. If you try one of those and find that it still doesn't work, please paste the full error message and stack trace here and we can look into it further! |
Beta Was this translation helpful? Give feedback.
-
Where specifically would you put this line of code?
It makes sense to be to put that inside the class that defines the schema but doing this results an the following error
|
Beta Was this translation helpful? Give feedback.
-
I guess what counts is, that validator has to be registered before any definitions actually use it. A couple options:
If none of those work, I bet we can find something else. |
Beta Was this translation helpful? Give feedback.
-
Understood. For now, I think and initializer makes the most sense to me. Thankyou for the assistance. |
Beta Was this translation helpful? Give feedback.
I guess what counts is, that validator has to be registered before any definitions actually use it.
A couple options:
iso_8601_duration_validator.rb
, and addrequire "graphql/(your path)/iso_8601_duration_validator.rb"
to any files that use that validator. That would make sure that validator was loaded and installed before those types are configured.app/graphql/my_app_schema.rb
, before the class definition). That will work, assuming that none of the types that use the validator are referenced outside the schema. …