Skip to content

Instantly share code, notes, and snippets.

@KronicDeth
Created June 4, 2016 01:54
Show Gist options
  • Save KronicDeth/8fc25a5c43b9964bc897c2a6b0450440 to your computer and use it in GitHub Desktop.
Save KronicDeth/8fc25a5c43b9964bc897c2a6b0450440 to your computer and use it in GitHub Desktop.
Using Alembic.Document.from_json in a Phoenix controller
defmodule MyApp.ApiController do
alias Alembic.Document
alias Alembic.Source
alias Plug.Conn
@doc """
Convert the `params` to a JSON API Document with `action` set as the `meta` `"action"`. If there a parsing
error, the error document is rendered as json to `conn` and the modified `conn` is returned. If there is no parsing
error then `{:ok, document}` is returned.
"""
@spec document_from_json(Conn.t, map, action :: atom) :: {:ok, Document.t} | Conn.t
def document_from_json(conn, params, action) do
with {:error, document} <- Document.from_json(
params,
%Alembic.Error{
meta: %{
"action" => action,
"sender" => :client
},
source: %Source{
pointer: ""
}
}
) do
render_json(conn, document, :unprocessable_entity)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment