elixir-maru / maru

Elixir RESTful Framework
https://maru.readme.io
BSD 3-Clause "New" or "Revised" License
1.32k stars 85 forks source link

List parameters #31

Closed ulfurinn closed 8 years ago

ulfurinn commented 8 years ago

I cannot for the life of me figure out how to declare a parameter that is a list of primitives. Looking at the sample in the guide:

  optional :preferences, type: List do
    requires :key
    requires :value
  end

this will declare a list of maps with "key" and "value", won't it? What if I want a list of integers?

Cifer-Y commented 8 years ago
 optional :preferences, type: List do
    requires :key
    requires :value
  end

above code means: params[:preferences] = [%{key: 1, value: 1}, %{key: 2, value: 2}]

If you just want a list of integers, I usually do as follow:

  1. in params declaration: requres :my_int_list, type: String
  2. and in your request you can post a json like: {"my_int_list": "1,2,3,4,5"}
  3. then in the endpoint, you can get a list of integers [1,2,3,4,5] by

    params[:my_int_list] |> String.split(",") |> Enum.map(&String.to_integer/1)

Or you can do that converting by using a custom maru type.

@ulfurinn Hope to be able to help you.

falood commented 8 years ago

@ulfurinn The explanation of List type by @Cifer-Y is completely correct. But there's no need to parse params within endpoint block. pipe types is helpful. if you post a json like {"my_int_list": "1,2,3,4,5"}, you can get {my_int_list: [1, 2, 3, 4, 5]} by

params do
  requires :my_int_list, type: fn s -> s |> String.split(",") |> Enum.map(&String.to_integer/1) end
end

And you can custom your own type to parse it if you use it continually.

I'm going to add a DSL like type: List[Integer] to make is easy to parse non-nested list. It's on the way.

ulfurinn commented 8 years ago

Forcing everything into a string is not an acceptable solution.

I'm going to add a DSL like type: List[Integer] to make is easy to parse non-nested list. It's on the way.

This would be great, provided that the swagger generator can also handle it correctly.

falood commented 8 years ago

I see. Thank you.

falood commented 8 years ago

I think this issue should be closed, maru swagger support one line list now. https://github.com/falood/maru_swagger/commit/c18e08c3f685df8d539821aeb0f86d891739b3c8