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

how to flatten nested errors? #151

Open
MathieuDerelle opened this issue Mar 4, 2020 · 1 comment
Open

how to flatten nested errors? #151

MathieuDerelle opened this issue Mar 4, 2020 · 1 comment

Comments

@MathieuDerelle
Copy link

MathieuDerelle commented Mar 4, 2020

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
Copy link
Author

MathieuDerelle commented Mar 4, 2020

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

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

1 participant