actor icon indicating copy to clipboard operation
actor copied to clipboard

Validating params or attributes

Open lifelofranco opened this issue 2 years ago • 4 comments

First of all, thanks for the great work! 💯

In interactor with the interactor-contracts gem, it's possible to validate a hash like this:

expects do
  required(:user).filled(type?: User)
  required(:params).schema do
    required(:email).filled(:str?)
    required(:first_name).filled(:str?)
    optional(:middle_name)
  end
end

Is there a similar way? Or a recommended way of achieving the same thing?

lifelofranco avatar Sep 26 '22 19:09 lifelofranco

Hi @lifelofranco!

Good call. There’s no such way to validate keys inside hashes with the current validation system.

One way you could do this out of the box would be using must. E.g.:

class CreateUser
  input :user, type: User
  input :params,
        must: {
          have_email: -> h { h[:email].present? },
          have_first_name: -> h { h[:first_name].present? },
        }

In the future perhaps we could build another validator for hashes that could perhaps look like this:

class CreateUser
  input :user, type: User
  input :params,
        hash: -> do
          input :email 
          input :first_name 
          input :middle_name, optional: true
        end

Edit: Fixed syntax for -> h

sunny avatar Sep 27 '22 07:09 sunny

Another option would be to add support for contracts like the interactor-contract gem does.

Is there any of these solutions you would like to try and implement @lifelofranco?

sunny avatar Dec 29 '22 18:12 sunny

I think there is a typo in the current example (h -> vs -> h).

class CreateUser
  input :user, type: User
  input :params,
        must: {
          have_email: -> (h) { h[:email].present? },
          have_first_name: -> (h) { h[:first_name].present? },
        }

pboling avatar Jul 12 '23 22:07 pboling

@pboling Good call! I’ve fixed the comment 👍🏻

sunny avatar Jul 13 '23 09:07 sunny