ja_serializer v0.18.1 JaSerializer.PhoenixView View Source

Use in your Phoenix.View to render jsonapi.org spec json.

See JaSerializer.Serializer for documentation on defining your serializer.

Usage example

defmodule PhoenixExample.ArticleView do
  use PhoenixExample.Web, :view
  use JaSerializer.PhoenixView # Or use in web/web.ex

  attributes [:title]

  has_many :comments,
    serializer: PhoenixExample.CommentsView,
    include: false,
    identifiers: :when_included
end

defmodule PhoenixExample.ArticlesController do
  use PhoenixExample.Web, :controller

  def index(conn, _params) do
    render conn, "index.json-api", data: Repo.all(Article)
  end

  def show(conn, %{"id" => id}) do
    article = Repo.get(Article, id) |> Repo.preload([:comments])
    render conn, "show.json-api", data: article,
      opts: [include: "comments"]
  end

  def create(conn, %{"data" => %{"attributes" => attrs}}) do
    changeset = Article.changeset(%Article{}, attrs)
    case Repo.insert(changeset) do
      {:ok, article} ->
        conn
        |> put_status(201)
        |> render("show.json-api", data: article)
      {:error, changeset} ->
        conn
        |> put_status(422)
        |> render(:errors, data: changeset)
    end
  end
end

Link to this section Summary

Functions

Extracts the data and opts from the keyword list passed to render and returns result of formatting.

Extracts the errors and opts from the data passed to render and returns result of formatting.

Link to this section Functions

Link to this function

render(serializer, data)

View Source

Extracts the data and opts from the keyword list passed to render and returns result of formatting.

Extracts the errors and opts from the data passed to render and returns result of formatting.

data is expected to be either an invalid Ecto.Changeset or preformatted errors as described in JaSerializer.ErrorSerializer.