Current section
Files
Jump to
Current section
Files
lib/structs/link.ex
defmodule Manganese.CoreKit.Structs.Link do
@moduledoc """
"""
alias Manganese.CoreKit.Structs
alias Manganese.CoreKit.Enumerations
@typedoc """
"""
@type t :: %Structs.Link{
method: Enumerations.HttpMethod.t,
uri: URI.t
}
@enforce_keys [
:uri,
:method
]
defstruct [
:uri,
method: :get
]
# Deserialization
@doc """
"""
@spec from_map(map) :: t
def from_map(%{
"method" => method,
"uri" => uri
}) do
%Structs.Link{
method: Enumerations.HttpMethod.from_string(method),
uri: URI.parse(uri)
}
end
@doc """
"""
@spec from_uri(Enumerations.HttpMethod.t, URI.t | String.t) :: t
def from_uri(method, %URI{} = uri) do
%Structs.Link{
method: method,
uri: uri
}
end
def from_uri(method, uri), do: from_uri method, URI.parse uri
@doc """
"""
@spec from_uri(URI.t | String.t) :: t
def from_uri(uri), do: from_uri :get, uri
# Serialization
@doc """
"""
@spec to_map(t) :: map
def to_map(%Structs.Link{
method: method,
uri: uri
}) do
%{
"method" => Enumerations.HttpMethod.to_string(method),
"uri" => URI.to_string(uri)
}
end
# Ecto type
@behaviour Ecto.Type
@impl Ecto.Type
def type, do: :map
@impl Ecto.Type
def cast(%Structs.Link{} = link), do: { :ok, link }
def cast(%{} = map), do: { :ok, from_map map }
def cast(nil), do: { :ok, nil }
def cast(_), do: :error
@impl Ecto.Type
def load(%{} = map), do: { :ok, from_map map }
def load(nil), do: { :ok, nil }
def load(_), do: :error
@impl Ecto.Type
def dump(%Structs.Link{} = link), do: { :ok, to_map link }
def dump(nil), do: { :ok, nil }
def dump(_), do: :error
end
defimpl String.Chars, for: Manganese.CoreKit.Structs.Link do
alias Manganese.CoreKit.Enumerations
def to_string(link) do
"#{Enumerations.HttpMethod.to_string link.method} #{URI.to_string link.uri}"
end
end