Current section
Files
Jump to
Current section
Files
lib/lab/agent.ex
defmodule Lab.Agent do
@moduledoc """
Documentation for Lab.Agent
"""
alias Lab.Client
@doc """
Gets all resource(s) available to the authenticated user.
Returns `{:ok, [%{}, %{}, ...]}`.
## Examples
iex> alias Lab.Agent
Lab.Agent
iex> Agent.all('/projects')
{:ok, [%{id: 1}, %{id: 2}, %{id: 3}]}
iex> Agent.all('/projects', per_page: 2)
{:ok, [%{id: 1}, %{id: 2}]}
"""
def all(resource, opts \\ []) do
res = Client.get(resource, [query: opts])
{:ok, Enum.map(res.body, fn(x) -> to_struct(resource, x) end)}
end
@doc """
Gets a single resource available to the authenticated user.
Returns `{:ok, %{}}`.
## Examples
iex> alias Lab.Agent
Lab.Agent
iex> Agent.get('/projects/1')
{:ok, [%{id: 1}}
"""
def get(resource, opts \\ []) do
res = Client.get(resource, [query: opts])
{:ok, to_struct(resource, res.body) }
end
defp to_struct(resource, string_map) do
bits = String.split(resource, "/")
str = bits
|> tl
|> List.first
|> String.replace_suffix("s", "")
|> String.capitalize
module = Module.concat("Lab", str)
map = atomize(string_map)
struct(module, map)
end
defp atomize(map) do
for {key, val} <- map, into: %{}, do: {String.to_atom(key), val}
end
end