Skip to content

Commit

Permalink
improve Consul.Kv public API
Browse files Browse the repository at this point in the history
  • Loading branch information
reset committed Jan 19, 2015
1 parent fea407f commit f151c36
Showing 1 changed file with 46 additions and 20 deletions.
66 changes: 46 additions & 20 deletions lib/consul/kv.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,46 @@
#

defmodule Consul.Kv do
alias Consul.Response
use Consul.Endpoint, handler: Consul.Handler.Kv

def fetch(key) do
req_get("kv/" <> key)
end
@separator "/"

def fetch(index, key, opts \\ [wait: "10m"]) do
req_get("kv/" <> key <> "?index=#{index}&wait=#{opts[:wait]}")
@spec fetch(binary | [binary], Keyword.t) :: {:ok, Response.t} | {:error, Response.t}
def fetch(key, opts \\ [])
def fetch(path, opts) when is_list(path) do
join_path(path) |> fetch(opts)
end

def fetch!(key) do
case fetch(key) do
{:ok, value} ->
value
{:error, response} ->
raise(Consul.ResponseError, response)
end
def fetch(key, opts) do
req_get(join_path(["kv", key]) <> "?" <> URI.encode_query(opts))
end

def fetch!(index, key, opts \\ [wait: "10m"]) do
case fetch(index, key, opts) do
@spec fetch!(binary | [binary], Keyword.t) :: Response.t | no_return
def fetch!(key, opts \\ [])
def fetch!(path, opts) when is_list(path) do
join_path(path) |> fetch!(opts)
end
def fetch!(key, opts) do
case fetch(key, opts) do
{:ok, value} ->
value
{:error, response} ->
raise(Consul.ResponseError, response)
end
end

@spec keys(binary | [binary]) :: {:ok, Response.t} | {:error, Response.t}
def keys(path) when is_list(path) do
join_path(path) |> keys
end
def keys(prefix) do
req_get("kv/" <> prefix <> "?keys")
req_get(join_path(["kv", prefix]) <> "?keys")
end

@spec keys!(binary | [binary]) :: Response.t | no_return
def keys!(path) when is_list(path) do
join_path(path) |> keys!
end
def keys!(prefix) do
case keys(prefix) do
{:ok, value} ->
Expand All @@ -46,21 +54,39 @@ defmodule Consul.Kv do
end
end

def put(key, value) do
case req_put("kv/" <> key, value) do
@spec put(binary | [binary], term, Keyword.t) :: {:ok, Response.t} | {:error, Response.t}
def put(key, value, opts \\ [])
def put(path, value, opts) when is_list(path) do
join_path(path) |> put(value, opts)
end
def put(key, value, opts) do
case req_put(join_path(["kv", key]) <> "?" <> URI.encode_query(opts), value) do
{:ok, %{body: body}} ->
body
error ->
error
end
end

def put!(key, value) do
case put(key, value) do
@spec put!(binary | [binary], term, Keyword.t) :: Response.t | no_return
def put!(key, value, opts \\ [])
def put!(path, value, opts) when is_list(path) do
join_path(path) |> put!(value, opts)
end
def put!(key, value, opts) do
case put(key, value, opts) do
{:error, response} ->
raise(Consul.ResponseError, response)
result ->
result
end
end

#
# Private
#

defp join_path(path) when is_list(path) do
Enum.join(path, @separator)
end
end

0 comments on commit f151c36

Please sign in to comment.