Skip to content

Instantly share code, notes, and snippets.

@Ajwah
Created September 1, 2021 12:13
Show Gist options
  • Save Ajwah/a2232838d3431c3e32343935d580df38 to your computer and use it in GitHub Desktop.
Save Ajwah/a2232838d3431c3e32343935d580df38 to your computer and use it in GitHub Desktop.
Convert %Plug.Conn{} Struct to JSON
defmodule Encoders do
alias Jason.Encoder
alias Encoder.BitString
defimpl Encoder, for: Tuple do
def encode(data, options) when is_tuple(data) do
data
|> Tuple.to_list()
|> Encoder.List.encode(options)
end
end
defimpl Encoder, for: PID do
def encode(pid, options) do
pid
|> inspect
|> BitString.encode(options)
end
end
defimpl Encoder, for: Function do
def encode(_, _) do
"Function"
end
end
end
# Then inside the module where you need to `conn |> Jason.encode`
require Protocol
Protocol.derive(Jason.Encoder, Plug.Conn)
Protocol.derive(Jason.Encoder, Plug.Conn.Unfetched)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment