-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.ex
50 lines (42 loc) · 991 Bytes
/
api.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
defmodule Viberex.API do
@moduledoc """
Work with Viber API
"""
alias Viberex.Config
def request(method, options \\ []) do
method
|> build_url
|> HTTPoison.post(build_request(options), headers())
|> response()
end
defp response(response) do
case decode_response(response) do
{:ok, result} ->
{:ok, result}
{:error, _} = error ->
error
end
end
defp decode_response(response) do
with {:ok, %HTTPoison.Response{body: body}} <- response,
{:ok, %{result: result}} <- Poison.decode(body, keys: :atoms),
do: {:ok, result}
end
defp build_url(method) do
Config.viber_api() <> "/" <> method
end
defp build_request(params) do
params =
params
|> Enum.filter(fn {_, v} -> v end)
|> Enum.into(%{})
|> Poison.encode!()
params
end
defp headers() do
[
"Content-Type": "application/json",
"X-Viber-Auth-Token": Config.auth_token
]
end
end