Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ result
.elixir_ls/
.elixir-tools/
.lexical/
.expert/

# Dialyzer
/priv/plts/

6 changes: 5 additions & 1 deletion config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ if config_env() == :dev do
api_key: System.fetch_env!("SUPABASE_KEY"),
env: config_env()

config :supabase, json_library: JSON
config :supabase_potion, json_library: JSON
end

if config_env() == :test do
config :supabase_potion, json_library: Jason
end
31 changes: 30 additions & 1 deletion lib/supabase.ex
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,37 @@ defmodule Supabase do
apply(__MODULE__, which, [])
end

@json_library Application.compile_env(:supabase, :json_library, Jason)
@json_library Application.compile_env(:supabase_potion, :json_library, Jason)

@doc "Returns the configured JSON encoding library for Supabase libraries."
@spec json_library :: Poison | Jason | JSON
def json_library, do: @json_library

@doc false
defguardp is_atom_opt(atom) when atom in ~w(atoms atoms!)a

@doc false
def decode_json(term, opts) do
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will be used internally on the other libraries to avoid duplicating this logic across the ecosystem

keys = Keyword.get(opts, :keys)

with {:ok, decoded} <- json_library().decode(term) do
if is_atom_opt(keys), do: atom_keys(decoded, keys), else: decoded
end
end

defp atom_keys(term, atom) when is_list(term) do
Enum.map(term, &atom_keys(&1, atom))
end

defp atom_keys(term, atom) when is_map(term) do
key =
if atom == :atoms!,
do: &String.to_existing_atom/1,
else: &String.to_atom/1

Map.new(term, fn
{k, v} when is_map(v) -> {key.(k), atom_keys(v, atom)}
{k, v} -> {key.(k), v}
end)
end
end
3 changes: 2 additions & 1 deletion test/supabase/fetcher/request_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,9 @@ defmodule Supabase.Fetcher.RequestTest do
test "sets a JSON-encoded body when given a map", %{client: client} do
body = %{key: "value"}
builder = Request.new(client) |> Request.with_body(body)
json = Supabase.json_library()

assert builder.body == Jason.encode_to_iodata!(%{"key" => "value"})
assert builder.body == json.encode_to_iodata!(%{"key" => "value"})
end

test "sets raw body when given a binary", %{client: client} do
Expand Down