Skip to content

custom type not suppot multiple types, raise Grape::Exceptions::ValidationErrors #2391

Description

@hsw15192617273

My project use a custom type like this.

module Types
  class Stage
    def self.parse(value)
      "#{value}haha"
    end

    def self.parsed?(value)
      value.is_a? String
    end
  end
end

And defined params like this.

params do
  optional :stage, types: [Array[::Types::Stage], ::Types::Stage]
  optional :province_id, types: [Array[Integer], Integer]
end
get :list do
  p declared(params)
end

There are no problem when I send these requests.

http GET 127.0.0.1:3000/api/list province_id[]==1 # {"stage"=>nil, "province_id"=>[1]}
http GET 127.0.0.1:3000/api/list province_id==1 # {"stage"=>nil, "province_id"=>1}

http GET 127.0.0.1:3000/api/list stage[]==1 # {"stage"=>["1haha"], "province_id"=>nil}

But when I send this request, raise a Grape::Exceptions::ValidationErrors

http GET 127.0.0.1:3000/api/list stage==1
# ~/.rbenv/versions/3.2.2/gemsets/gems/grape-2.0.0/lib/grape/endpoint.rb:363:in `run_validators'
# ~/.rbenv/versions/3.2.2/gemsets/gems/grape-2.0.0/lib/grape/endpoint.rb:258:in `block in run'

I think there is a problem with the call method of lib/grape/validations/types/custom_type_collection_coercer.rb.

def call(value)
  coerced = value.map do |item|
    coerced_item = super(item)

    return coerced_item if coerced_item.is_a?(InvalidValue)

    coerced_item
  end

  @set ? Set.new(coerced) : coerced
end

When use multiple types, there is a possibility that value is not an array.
Maybe should determine unless value.is_a?(Array) and return InvalidValue.new, like DryTypeCoercer#call

If this is correct, I can create a PR to fix it.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions