Skip to content

Instantly share code, notes, and snippets.

@DavidAntaramian
Created February 4, 2017 23:28
Show Gist options
  • Save DavidAntaramian/e5850cddc4011710712c7d56eab113ad to your computer and use it in GitHub Desktop.
Save DavidAntaramian/e5850cddc4011710712c7d56eab113ad to your computer and use it in GitHub Desktop.
defmodule Stripe.PaymentMethod do
@spec list(Account.id, Keyword.t) :: {:ok, boolean, [t] | []} | {:error, Exception.t}
def list(account_id, opts \\ []) do
query =
%{
object: "card",
ending_before: Keyword.get(opts, :ending_before),
limit: Keyword.get(opts, :limit),
starting_after: Keyword.get(opts, :starting_after)
}
|> Stripe.drop_nil_keys()
|> URI.encode_query()
endpoint = "customers/" <> account_id <> "/sources?" <> query
case Stripe.request(:get, endpoint, nil, %{}, []) do
{:ok, result} ->
payment_methods =
Map.get(result, "data")
|> Enum.map(&decode_api_map/1)
has_more = Map.get(result, "has_more")
{:ok, has_more, payment_methods}
{:error, error} ->
{:error, error}
end
end
@spec stream(Account.id, Keyword.t) :: Stream.t
def stream(account_id, opts \\ []) do
initial_opts = Keyword.take(opts, [:starting_after, :ending_before])
ongoing_opts = Keyword.take(opts, [:ending_before])
Stream.resource(fn ->
{true, nil}
end,
fn
{true, starting_after} ->
list_opts =
if is_nil(starting_after) do
initial_opts
else
Keyword.put(ongoing_opts, :starting_after, starting_after)
end
case list(account_id, list_opts) do
{:ok, true, results} ->
last_result_id =
List.last(results)
|> Map.fetch!(:id)
{results, {true, last_result_id}}
{:ok, false, results} ->
{results, false}
end
false ->
{:halt, false}
end,
fn _ -> :ok end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment