Skip to content

Commit

Permalink
Remove nil fields in request params
Browse files Browse the repository at this point in the history
  • Loading branch information
anronin committed May 31, 2016
1 parent 42650ab commit 9037fc3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
10 changes: 2 additions & 8 deletions lib/nadia.ex
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ defmodule Nadia do
def get_chat_member(chat_id, user_id) do
request("getChatMember", chat_id: chat_id, user_id: user_id)
end

@doc """
Use this method to send answers to callback queries sent from inline keyboards.
The answer will be displayed to the user as a notification at the top of the chat
Expand Down Expand Up @@ -630,13 +630,7 @@ defmodule Nadia do
"""
@spec answer_inline_query(binary, [Nadia.Model.InlineQueryResult.t], [{atom, any}]) :: :ok | {:error, Error.t}
def answer_inline_query(inline_query_id, results, options \\ []) do
encoded_results = results
|> Enum.map(fn result ->
for {k, v} <- Map.from_struct(result), v != nil, into: %{}, do: {k, v}
end)
|> Poison.encode!
args = [inline_query_id: inline_query_id, results: encoded_results]

args = [inline_query_id: inline_query_id, results: results]
request("answerInlineQuery", args ++ options)
end
end
19 changes: 18 additions & 1 deletion lib/nadia/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,31 @@ defmodule Nadia.API do
defp build_request(params, file_field) do
params = params
|> Keyword.update(:reply_markup, nil, &(Poison.encode!(&1)))
|> Enum.filter_map(fn {_, v} -> v end, fn {k, v} -> {k, to_string(v)} end)
|> Enum.filter_map(fn {_, v} -> v end, fn {k, v} -> {k, drop_nil_fields(v)} end)
if !is_nil(file_field) and File.exists?(params[file_field]) do
build_multipart_request(params, file_field)
else
{:form, params}
end
end

defp drop_nil_fields(value) when is_list(value) do
value
|> Enum.map(fn value ->
for {k, v} <- Map.from_struct(value), v != nil, into: %{}, do: {k, drop_nil_fields(v)}
end)
|> Poison.encode!
end

defp drop_nil_fields(value) when is_map(value) do
value
|> Map.from_struct
|> Enum.filter(fn {_, v} -> v != nil end)
|> Enum.into(%{})
end

defp drop_nil_fields(value), do: to_string(value)

@doc """
Generic method to call Telegram Bot API.
Expand Down

0 comments on commit 9037fc3

Please sign in to comment.