jsonapi v0.3.0 JSONAPI.View

A View is simply a module that defines certain callbacks to configure proper rendering of your JSONAPI documents.

defmodule PostView do
  use JSONAPI.View

  def fields, do: [:id, :text, :body]
  def type, do: "post"
  def relationships do
    [author: UserView,
     comments: CommentView]
  end
end

defmodule UserView do
  use JSONAPI.View

  def fields, do: [:id, :username]
  def type, do: "user"
  def relationships, do: []
end

defmodule CommentView do
  use JSONAPI.View

  def fields, do: [:id, :text]
  def type, do: "comment"
  def relationships do
    [user: {UserView, :include}]
  end
end

You can now call UserView.show(user, conn, conn.params) and it will render a valid jsonapi doc.

Relationships

Currently the relationships callback expects that a map is returned configuring the information you will need. If you have the following Ecto Model setup

defmodule User do
  schema "users" do
    field :username
    has_many :posts
    has_one :image
  end
end

and the includes setup from above. If your Post has loaded the author and the query asks for it then it will be loaded.

So for example: GET /posts?include=post.author if the author record is loaded on the Post, and you are using the JSONAPI.QueryParser it will be included in the includes section of the JSONAPI document.

If you always want to include a relationship. First make sure its always preloaded and then use the [user: {UserView, :include}] syntax in your includes function. This tells the serializer to always include if its loaded.