From 9037fc34735f49ec63f6a6c7cfe0d2e0f845528b Mon Sep 17 00:00:00 2001 From: "Andrey N. Ronin" Date: Wed, 25 May 2016 14:33:38 +0400 Subject: [PATCH] Remove nil fields in request params --- lib/nadia.ex | 10 ++-------- lib/nadia/api.ex | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/lib/nadia.ex b/lib/nadia.ex index 248cc32..e2b57b8 100644 --- a/lib/nadia.ex +++ b/lib/nadia.ex @@ -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 @@ -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 diff --git a/lib/nadia/api.ex b/lib/nadia/api.ex index ed9b4fc..3092a25 100644 --- a/lib/nadia/api.ex +++ b/lib/nadia/api.ex @@ -40,7 +40,7 @@ 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 @@ -48,6 +48,23 @@ defmodule Nadia.API do 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.