rubbergloves v0.0.3 Rubbergloves.Struct
A series of macros to define how to convert from a raw %{} map to a well defined struct.
Supports nested struct mapping, and global conventions.
Using Rubbergloves.Struct give you access to the defmapping
module that defines how to convert the input into your stuct.
Once in a defmapping block, two macros are avaliable for you:
keys/1
Takes a function that retrieves the key of the struct and returns the key in the map to collect the data from.
i.e. to map input in the form
%{ "someKeyName" => "value"}
to a struct likedefstruct [:some_key_name]
overrides/2
Takes the struct key and a keyword list of override options.
Override options can include:
:key
- A string/atom value of the key in the input map
- Or a function in the format struct_key -> expected_key
:value
- A hard coded value to use despite whats in the input map.
- Or more useful a function in the format input_value -> transformed_value
- For nested structs, use the one/many macros to apply nested mapping rules
Given Input
params = %{
"username" => "test",
"password" => "password"
"meta" => %{
"type" => "UserPass"
}
}
With Definitions
defmodule MyApp.Requests.LoginRequestMeta do
defstruct [:type ]
defmapping do
keys &CamelCaseKeyResolver.resolve/1
end
end
defmodule MyApp.Requests.LoginRequest do
use Rubbergloves.Struct
alias MyApp.Requests.LoginRequestMeta
defstruct [:username, :password, :hashed_password, :meta]
defmapping do
keys &CamelCaseKeyResolver.resolve/1
override :hashed_password, key: "password", value: &hash_password_input/1
override :meta, value: one(LoginRequestMeta)
end
@impl validate
def validate(request) do
# Validate however you like
end
# Custom methods to map your input to struct values
def hash_password_input(_val) do
"SOMEHASHED_PASSWORD_EXAMPLE"
end
end