Current section
Files
Jump to
Current section
Files
lib/silk_client.ex
defmodule SilkClient do
defstruct [:url, :api]
def client(silk_url, opts \\ []) do
%__MODULE__{url: silk_url, api: ((opts[:fake] && SilkClient.Fake) || SilkClient.Real)}
end
def put_record(client, topic, payload) when not is_nil(client) and not is_nil(topic) and not is_nil(payload) do
post(client, "records/#{topic}", payload)
end
#curl -s -H'accept: application/json' -H'content-type: application/json' "localhost:4000/api/records/test-topic?limit=2&last_seen_id=400"
def get_records(client, topic) when not is_nil(client) and not is_nil(topic) do
get_records(client, topic, nil, nil)
end
def get_records(client, topic, nil, nil) when not is_nil(client) and not is_nil(topic) do
get(client, "records/#{topic}")
end
def get_records(client, topic, limit, last_seen_id) when not is_nil(client) and not is_nil(topic) and not is_nil(limit) and not is_nil(last_seen_id) do
get(client, "records/#{topic}?limit=#{limit}&last_seen_id=#{last_seen_id}")
end
defp get(client, path) do
client.api.get(client, path)
end
defp post(client, path, payload) do
client.api.post(client, path, payload)
end
end
defmodule SilkClient.Fake do
require Logger
def get(_client, _path) do
%{}
end
def post(_client, _path, _payload) do
%{}
end
end
defmodule SilkClient.Real do
require Logger
def get(client, path) do
path = api_path(client, path)
Logger.debug "#{__MODULE__}.#{inspect(__ENV__.function)} GET #{path}"
case HTTPoison.get(path, [{"Accept", "application/json"}]) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
Logger.debug "#{__MODULE__}.#{inspect(__ENV__.function)} 200 response"
Poison.decode!(body)
{_, resp} ->
Logger.error :io_lib.format("#{__MODULE__}.#{inspect(__ENV__.function)} GET ~s non-2xx response: ~s", [path, inspect(resp)])
end
end
def post(client, path, payload) do
path = api_path(client, path)
Logger.debug "#{__MODULE__}.#{inspect(__ENV__.function)} POST #{path} payload=#{inspect(payload)}"
body = %{"payload" => Poison.encode!(payload)} |> Poison.encode!()
resp = HTTPoison.post(path, body, [{"Accept", "application/json"}, {"Content-Type", "application/json"}])
case resp do
{:ok, %HTTPoison.Response{status_code: 201, body: body}} ->
Logger.debug "#{__MODULE__}.#{inspect(__ENV__.function)} 201 response"
Poison.decode!(body)
_ ->
Logger.error :io_lib.format("#{__MODULE__}.#{inspect(__ENV__.function)} POST ~s non-2xx response: ~s", [path, inspect(resp)])
end
end
defp api_path(client, part) do
Path.join([client.url, part])
end
end