aboutsummaryrefslogtreecommitdiff
path: root/lib/zendex.ex
blob: e697d8b9627a45927fe86361b3eacde7fcf1fa87 (plain)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
defmodule Zendex do
  @moduledoc """
  HTTPoison Zendesk Client
  """
  use HTTPoison.Base
  alias Zendex.Connection
  alias HTTPoison.Response

  @user_agent [{"user-agent", "zendex"}]

  @type response :: {integer, any} | map

  @spec process_response_body(binary) :: term
  def process_response_body(""), do: nil
  def process_response_body(body), do: Poison.decode!(body)

  @spec process_response(HTTPoison.Response.t) :: response
  def process_response(%Response{status_code: 200, body: body}) do
    body
  end
  def process_response(%Response{status_code: status_code, body: body}) do
    {status_code, body}
  end

  @spec delete!(binary, Zendex.Connection.t, binary) :: any | {integer, any}
  def delete!(path, connection, body \\ "") do
    _request(:delete, url(connection, path), connection.authentication, body)
  end

  @spec post(binary, Zendex.Connection.t, binary) :: any | {integer, any}
  def post(path, connection, body \\ "") do
    _request(:post, url(connection, path), connection.authentication, body)
  end

  @spec post!(binary, Zendex.Connection.t, binary) :: any | {integer, any}
  def post!(path, connection, body \\ "") do
    {201, resp} = post(path, connection, body)
    resp
  end

  @doc """
  Underlying utility retrieval function

  The options passed affect both the return value and, ultimately, the number
  of requests made to Zendesk.

  Options:
  * `pagination` - can be `:none`, or `:auto`. Defaults to `:none`.
  """
  @spec get!(binary, Zendex.Connection.t, Keyword.t, Keyword.t) :: term
  def get!(path, connection, params \\ [], options \\ []) do
    url =
      connection
      |> url(path)
      |> add_params_to_url(params)

    {auth, _} = Map.split(connection, [:authentication])

    case pagination(options) do
      nil ->
        :get
        |> request_stream(url, auth, "", :one_page)
        |> realize_if_needed
      :none ->
        :get
        |> request_stream(url, auth, "", :one_page)
        |> realize_if_needed
      :auto ->
        :get
        |> request_stream(url, auth)
        |> realize_if_needed
    end
  end

  def _request(method, url, auth, body \\ "") do
    json_request(method, url, body, authorization_header(auth, @user_agent))
  end

  def json_request(method, url, body \\ "", headers \\ [], options \\ []) do
    raw_request(method, url, Poison.encode!(body), headers, options)
  end

  defp pagination(options) do
    options
      |> Keyword.get(:pagination)
      |> case do
        nil -> Application.get_env(:zendex, :pagination, nil)
        x -> x end
  end

  def raw_request(method, url, body \\ "", headers \\ [], options \\ []) do
    method
    |> request!(url, body, headers, options)
    |> process_response
  end

  def request_stream(method, url, auth, body \\ "", override \\ nil) do
    method
    |> request_with_pagination(url, auth, Poison.encode!(body))
    |> stream_if_needed(override)
  end
  defp stream_if_needed(result = {status_code, _}, _)
    when is_number(status_code), do: result
  defp stream_if_needed({body, nil, _}, _), do: body
  defp stream_if_needed({body, _, _}, :one_page), do: body
  defp stream_if_needed(initial_results, _) do
    Stream.resource(
      fn -> initial_results end,
      &process_stream/1,
      fn _ -> nil end)
  end

  defp realize_if_needed(x)
    when is_tuple(x) or is_binary(x) or is_list(x) or is_map(x), do: x
  defp realize_if_needed(stream), do: Enum.to_list(stream)

  defp process_stream({[], nil, _}), do: {:halt, nil}
  defp process_stream({[], next, auth}) do
    :get
    |> request_with_pagination(next, auth, "")
    |> process_stream
  end
  defp process_stream({items, next, auth}) when is_list(items) do
    {items, {[], next, auth}}
  end
  defp process_stream({item, next, auth}) do
    {[item], {[], next, auth}}
  end

  @spec request_with_pagination(atom, binary, Connection.auth, binary) ::
    {binary, binary, Zendex.Connection.auth}
  def request_with_pagination(method, url, auth, body \\ "") do
    resp = request!(method,
                    url,
                    Poison.encode!(body),
                    authorization_header(auth, @user_agent),
                    [])
    case process_response(resp) do
      x when is_tuple(x) -> x
      _ -> pagination_tuple(resp, auth)
    end
  end

  @spec pagination_tuple(HTTPoison.Response.t, Connection.auth) ::
    {binary, binary, Connection.auth}
  defp pagination_tuple(%Response{body: body} = resp, auth) do
    {process_response(resp), next_link(body), auth}
  end

  defp next_link(%{"next_page" => next}), do: next
  defp next_link(_), do: nil

  defp url(_client = %{base_url: base_url}, path = "/" <> _) do
    base_url <> path
  end

  @doc """
  Take an existing URI and add addition parameters, merging as necessary

  ## Examples
      iex> add_params_to_url("http://example.com/wat", [])
      "http://example.com/wat"
      iex> add_params_to_url("http://example.com/wat", [q: 1])
      "http://example.com/wat?q=1"
      iex> add_params_to_url("http://example.com/wat", [q: 1, t: 2])
      "http://example.com/wat?q=1&t=2"
      iex> add_params_to_url("http://example.com/wat", %{q: 1, t: 2})
      "http://example.com/wat?q=1&t=2"
      iex> add_params_to_url("http://example.com/wat?q=1&t=2", [])
      "http://example.com/wat?q=1&t=2"
      iex> add_params_to_url("http://example.com/wat?q=1", [t: 2])
      "http://example.com/wat?q=1&t=2"
      iex> add_params_to_url("http://example.com/wat?q=1", [q: 3, t: 2])
      "http://example.com/wat?q=3&t=2"
      iex> add_params_to_url("http://example.com/wat?q=1&s=4", [q: 3, t: 2])
      "http://example.com/wat?q=3&s=4&t=2"
      iex> add_params_to_url("http://example.com/wat?q=1&s=4", %{q: 3, t: 2})
      "http://example.com/wat?q=3&s=4&t=2"

  """
  @spec add_params_to_url(binary, list) :: binary
  def add_params_to_url(url, params) do
    url
    |> URI.parse
    |> merge_uri_params(params)
    |> to_string
  end

  @spec merge_uri_params(URI.t, list) :: URI.t
  defp merge_uri_params(uri, []), do: uri
  defp merge_uri_params(%URI{query: nil} = uri, params)
      when is_list(params) or is_map(params) do
    uri
    |> Map.put(:query, URI.encode_query(params))
  end
  defp merge_uri_params(%URI{} = uri, params)
      when is_list(params) or is_map(params) do
    uri
    |> Map.update!(:query, fn q ->
      q
      |> URI.decode_query
      |> Map.merge(param_list_to_map_with_string_keys(params))
      |> URI.encode_query
    end)
  end

  @spec param_list_to_map_with_string_keys(list) :: map
  defp param_list_to_map_with_string_keys(list)
      when is_list(list) or is_map(list) do
    for {key, value} <- list, into: Map.new do
      {"#{key}", value}
    end
  end

  @spec authorization_header(Connection.auth, list) :: list
  def authorization_header(%{authentication: authentication}, headers) do
    headers ++ [{"Authorization", "Basic #{authentication}"}]
  end
  def authorization_header(_, headers), do: headers

end