Params
params variable
TODO
Type
There are a number of build-in Types, including: String Integer Float Boolean CharList Atom and File.
You can also use them as :string :integer :float :boolean :char_list :atom and :file.
An Maru.Exceptions.InvalidFormatter[reason: :illegal] exception will be raised on type change error.
Atom Parser
Atomtype parameter is parsed byString.to_existing_atom, so avaluesvalidator is recommended.
Validators
There're three build-in validators: regexp values and allow_blank, you can use them like this:
params do
requires :id, type: :integer, regexp: ~r/^[0-9]+$/
requires :sex, type: :atom, values: [:female, :male], default: :female
optional :age, type: :integer, values: 18..65
end
An Maru.Exceptions.UndefinedValidator exception will be raised if validator not defined.
An Maru.Exception.Validation exception will be raised on validators check error.
Custom validators
defmodule Maru.Validations.Length do
def validate_param!(attr_name, value, option) do
byte(value) in option ||
Maru.Exceptions.Validation |> raise [param: attr_name, validator: :length, value: value, option: option]
end
end
params do
requires :text, length: 2..6
end
Nested Params
In general, Nested Params can be used in the same way as grape except that we should use List and Map in Elixir instead of Array and Hash in Ruby.
params do
optional :preferences, type: List do
requires :key
requires :value
end
requires :name, type: Map do
requires :first_name
requires :last_name
end
end
mutually_exclusive, exactly_one_of and at_least_one_of can also be used in the same way as grape except that we should use an explicit List.
params do
requires :food do
optional :meat
optional :fish
optional :rice
at_least_one_of [:meat, :fish, :rice]
end
group :drink do
optional :beer
optional :wine
optional :juice
exactly_one_of [:beer, :wine, :juice]
end
optional :dessert do
optional :cake
optional :icecream
mutually_exclusive [:cake, :icecream]
end
end
Reusable Params
You can define reusable params using helpers.
defmodule API do
helpers :name do
optional :first_name
optional :last_name
end
params do
use :name
end
get do
...
end
end
You can also define reusable params using shared helpers.
defmodule SharedParams do
use Maru.Helper
params :period do
optional :start_date
optional :end_date
end
params :pagination do
optional :page, type: Integer
optional :per_page, type: Integer
end
end
defmodule API do
helpers SharedParams
params do
use [:period, :pagination]
end
get do
...
end
end
Updated less than a minute ago
