-
Notifications
You must be signed in to change notification settings - Fork 3
Validating query parameters
Sometimes, you may want to validate the query parameters passed to your operation. For instance,
let's suppose your articles/index
operation accepts a by_user
filter which is supposed to be a
user ID, and you want to verify this value is an integer, if present.
You can accomplish this quite easily by embedding a dry-validation schema in your operation. You can write your operation as follows:
# app/resources/api/v1/article/operation/index.rb
module API
module V1
module Article
module Operation
class Index < Pragma::Operation::Index
Schema = Dry::Validation.Schema do
optional(:user_id).maybe(:int?)
end
step :validate_params!, before: 'retrieve', fail_fast: true
def validate_params!(options, params:, **)
result = Schema.(params)
return true if result.success?
options['result.response'] = Pragma::Operation::Response::UnprocessableEntity.new(
errors: result.errors,
).decorate_with(Pragma::Decorator::Error)
false
end
end
end
end
end
end
As you can see, we are basically specifying a validation schema just as we do in contracts, except that the schema will not be synced with a model and is just used to ensure the parameters passed to the operation are correct.
Note that, while the example uses an Index operation, you can do this for any operation, including Create, Update and Destroy (even though passing query parameters to non-GET operations is highly discouraged).