Current section

Files

Jump to
bingex lib bingex swap data close_all_positions_data.ex
Raw

lib/bingex/swap/data/close_all_positions_data.ex

defmodule Bingex.Swap.CloseAllPositionsData do
@moduledoc """
Parses and structures response data for closing all swap positions on BingX.
This module extracts and formats the list of successfully and unsuccessfully closed positions
from API responses. It also provides a utility to embed the parsed data into a `Bingex.API.Reply`.
"""
alias Bingex.API.Reply
import Bingex.Helpers
import Bingex.Convertors
defstruct [:failed, :succeeded]
@type t() :: %__MODULE__{
succeeded: [binary()],
failed: [binary()]
}
@spec embed_in_reply(Reply.t()) :: Reply.t(t())
def embed_in_reply(%Reply{payload: payload} = reply) do
case decode(payload) do
{:ok, data} -> Reply.put_data(reply, data)
:error -> reply
end
end
def embed_in_reply(%Reply{data: _} = reply), do: reply
@spec decode(any()) :: {:ok, t()} | :error
def decode(%{"data" => data}) when is_map(data) do
struct = %__MODULE__{
succeeded: decode_values(data, "success"),
failed: decode_values(data, "failed")
}
{:ok, struct}
end
def decode(_data), do: :error
defp decode_values(%{} = data, key) do
values = get_and_transform(data, key, [], &to_list/1) || []
values
|> Enum.map(&to_non_empty_binary/1)
|> reject_nils()
end
end