elixir - Limit fields of JSON response -
i'm using phoenixframework , library poison. current i'm working on rest api. need encode model book
in 2 different ways.
- in list of books base informations (
get /books
) - in detailed view informations (
get /book/1
)
get /books
{ "books": [ { "id": 1, "name": "book one" }, { "id": 2, "name": "book two" }, // ... ] }
get /books/1
{ "book": { "id": 1, "name": "book one", "description": "this book one.", "author": "max mustermann", // ... } }
encoder of book
defimpl poison.encoder, for: myproject.book @attributes [:id, :name, :description, :author] def encode(project, _options) project |> map.take(@attributes) |> poison.encode! end end
snippet controller
def index(conn, _params) books = repo.all(book) json(conn, %{books: books}) end
how limit fields? search option :only
or :exclude
. has experience problem?
thanks help!
you can use render_many/4 , render_one/4:
defmodule myapp.bookview def render("index.json", %{books: books}) render_many(books, __module__, "book.json") end def render("show.json", %{book: book}) render_one(book, __module__, "full_book.json") end def render("book.json", %{book: book}) %{ id: book.id, name: book.name } end def render("full_book.json", %{book: book}) %{ id: book.id, name: book.name, description: description, author: book.author ... } end end
please note name in assigns (2nd argument of render) determined module. see render many many relationship json in phoenix framework example of using different name.
you can call controller using:
render(conn, "index.json", books: repo.all(book)) render(conn, "show.json", book: repo.get(book, 1))
Comments
Post a Comment