cypriss / mutations

Compose your business logic into commands that sanitize and validate input.
MIT License
1.39k stars 93 forks source link

how to flatten nested errors? #151

Open MathieuDerelle opened 4 years ago

MathieuDerelle commented 4 years ago

is there a method to get all the errors in an array ? (even if they are nested)

when validating a hash for instance :

  required do
    hash :params do
      required do
        string :action, strict: true
        integer :id
      end
    end
  end
MathieuDerelle commented 4 years ago

a workaround for my json api atm :

output['errors'] = flatten_outcome_errors(outcome.errors)
    def flatten_outcome_errors(nested_errors, memo_path = [], memo_flat_errors = [])
      return if nested_errors.nil? # can happen in arrays

      nested_errors.each_with_object(memo_flat_errors) do |(key, value), memo|
        path = memo_path + [key]

        case value
        when Array
          value.each_with_index do |val, index|
            path = memo_path + ["#{key}[#{index}]"]
            flatten_outcome_errors(val, path, memo)
          end
        when Hash
          flatten_outcome_errors(value, path, memo)
        when Mutations::ErrorAtom
          memo << export_mutation_error(value, path)
        else
          # is it even possible ?
        end
      end
    end

    def export_mutation_error(e, path)
      # e.instance_variable_get(:@key) already included in path
      {
        key: path.join('.'),
        symbol: e.instance_variable_get(:@symbol),
        message: e.instance_variable_get(:@message)
      }
    end

EDIT: updated my code