Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prefers the built-in JSON library from Elixir 1.18.x when it's available #650

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 5 additions & 1 deletion lib/mix/tasks/openapi.spec.json.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,13 @@ defmodule Mix.Tasks.Openapi.Spec.Json do
defp maybe_start_app(true), do: Mix.Task.run("app.start")
defp maybe_start_app(_), do: Mix.Task.run("app.config", preload_modules: true)

# Unfortunately, the built-in JSON module in Elixir 1.18.x doesn't support the `pretty` option
# So we need to take Jason or Poison to be able to support this feature
defp json_encoder(), do: Enum.find([Jason, Poison], &Code.ensure_loaded?/1)

defp encode(spec, %{pretty: pretty}) do
spec
|> OpenApiSpex.OpenApi.json_encoder().encode(pretty: pretty)
|> json_encoder().encode(pretty: pretty)
Copy link
Contributor

@zorbash zorbash Mar 10, 2025

Choose a reason for hiding this comment

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

We can provide a helpful error message when so suitable encoder is configured.

Currently it fails with:

** (UndefinedFunctionError) function nil.encode/2 is undefined
    nil.encode(%{"components" => %{"responses" => %{"unprocessable_entity" => %{"content" => %{"application/json" => %{"schema" => %{"type" => "object", "x-struct" => nil, "x

We can follow this pattern in Plug. https://github.com/elixir-plug/plug/blob/main/lib/plug/parsers/json.ex#L66

defp encode(spec, %{pretty: pretty}) do
  encoder = json_encoder()
  
  validate_encoder!(encoder)

  encoder.encode(pretty: pretty)
end

Copy link
Author

Choose a reason for hiding this comment

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

Ah right that is a good one. Will fix that 👍 ❤️

Copy link
Contributor

Choose a reason for hiding this comment

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

It appears we'll need a few more changes since the built-in JSON module does not export an encode/2 function but only an encode!/2.

Copy link
Author

Choose a reason for hiding this comment

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

I'll tackle those cases too 🫡

|> case do
{:ok, json} ->
"#{json}\n"
Expand Down
8 changes: 4 additions & 4 deletions lib/open_api_spex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ defmodule OpenApiSpex do
- ensures the schema is linked to the module by "x-struct" extension property
- defines a struct with keys matching the schema properties
- defines a @type `t` for the struct
- derives a `Jason.Encoder` and/or `Poison.Encoder` for the struct
- derives a `JSON.Encoder`, `Jason.Encoder` and/or `Poison.Encoder` for the struct

See `OpenApiSpex.Schema` for additional examples and details.

Expand Down Expand Up @@ -238,8 +238,8 @@ defmodule OpenApiSpex do
- `:struct?` (boolean) - When false, prevents the automatic generation
of a struct definition for the schema module.
- `:derive?` (boolean) When false, prevents the automatic generation
of a `@derive` call for either `Poison.Encoder`
or `Jason.Encoder`. Using this option can
of a `@derive` call for either `JSON.Encoder`
Copy link
Contributor

Choose a reason for hiding this comment

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

Add comma after JSON.Encoder.

`Poison.Encoder` or `Jason.Encoder`. Using this option can
prevent "... protocol has already been consolidated ..."
compiler warnings.
"""
Expand All @@ -262,7 +262,7 @@ defmodule OpenApiSpex do

if Map.get(@schema, :"x-struct") == __MODULE__ do
if Keyword.get(unquote(opts), :derive?, true) do
@derive Enum.filter([Poison.Encoder, Jason.Encoder], &Code.ensure_loaded?/1)
@derive Enum.filter([JSON.Encoder, Poison.Encoder, Jason.Encoder], &Code.ensure_loaded?/1)
end

if Keyword.get(unquote(opts), :struct?, true) do
Expand Down
4 changes: 2 additions & 2 deletions lib/open_api_spex/open_api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ defmodule OpenApiSpex.OpenApi do
"""
@callback spec() :: t

@json_encoder Enum.find([Jason, Poison], &Code.ensure_loaded?/1)
@json_encoder Enum.find([JSON, Jason, Poison], &Code.ensure_loaded?/1)
@yaml_encoder nil
@vendor_extensions ~w(
x-struct
Expand All @@ -80,7 +80,7 @@ defmodule OpenApiSpex.OpenApi do

def json_encoder, do: @json_encoder

for encoder <- [Poison.Encoder, Jason.Encoder] do
for encoder <- [JSON.Encoder, Poison.Encoder, Jason.Encoder] do
Copy link
Contributor

Choose a reason for hiding this comment

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

My suggestion would be to make JSON.Encoder the last option, so that it's only picked up as a fallback if the application doesn't depend on a library.

Copy link
Author

Choose a reason for hiding this comment

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

Could be but I think it's even nicer to let the user actively choose the preferred encoder. Just like Phoenix does: https://hexdocs.pm/phoenix/Phoenix.html

It could well be that another hex package in a developers project already include Jason or Poison.

But that will require some more effort to implement 😄

Copy link
Contributor

Choose a reason for hiding this comment

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

I'd advise against application configuration for the JSON encoder in open_api_spex for the following reasons:

if Code.ensure_loaded?(encoder) do
defimpl encoder do
def encode(api_spec = %OpenApi{}, options) do
Expand Down
2 changes: 1 addition & 1 deletion lib/open_api_spex/plug/render_spec.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ defmodule OpenApiSpex.Plug.RenderSpec do

@behaviour Plug

@json_encoder Enum.find([Jason, Poison], &Code.ensure_loaded?/1)
@json_encoder Enum.find([JSON, Jason, Poison], &Code.ensure_loaded?/1)

@impl Plug
def init(opts), do: opts
Expand Down