Skip to content

Instantly share code, notes, and snippets.

@nickgartmann
Created August 13, 2015 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickgartmann/04886d379d1a58847ccf to your computer and use it in GitHub Desktop.
Save nickgartmann/04886d379d1a58847ccf to your computer and use it in GitHub Desktop.
Example output from a JSONAPI generator
mix jsonapi.gen.templates
mix phoenix.gen.json Test testing name:string email:string
defmodule Testing.Testing.TestController do
use Testing.Web, :controller
alias Testing.ChangesetView
import Ecto.Query
plug :scrub_params, "data" when action in [:create, :update]
# GET /tests/:id
def show(conn, %{"id" => id}) do
test = Repo.get!(Testing.Test, id)
render conn, "show.json", data: test
end
# GET /tests
def index(conn, params) do
filter = conn.assigns[:jsonapi][:filter]
tests = from(t in Testing.Test)
|> JSONAPI.Query.add_query_paging(conn.assigns[:jsonapi])
|> Repo.all
render conn, "index.json", data: tests, params: params
end
# POST /tests
def create(conn, json=%{"format" => "json"}) do
changeset = Test.changeset(%Test{}, Dict.get(json, "data", %{}))
case Repo.insert(changeset) do
{:ok, test} ->
conn
|> put_resp_header("location", test_path(Endpoint, :show, test.id))
|> put_status(201)
|> render "show.json", data: test
{:error, errors} ->
put_status(conn, 400)
|> render ChangesetView, "error.json", changeset: changeset
end
end
# PUT /tests/:id
def update(conn, json=%{"format" => "json", "id" => id}) do
test = Repo.get!(Test, id)
changeset = Test.changeset(test, Dict.get(json, "data", %{}))
case Repo.update(changeset) do
{:ok, test} ->
render conn, "show.json", data: test
{:error, changeset} ->
put_status(conn, 400)
|> render ChangesetView, "error.json", changeset: changeset
end
end
# DELETE /tests/:id
def delete(conn, %{"format" => "json", "id" => id}) do
test = Repo.get!(Test, id)
|> Repo.delete!
send_resp(conn, 204, "") |> halt
end
end
defmodule Testing.TestView do
use Testing.Web, :view
def type(), do: "test"
def attributes(test) do
Map.take(test, [:email, :name])
end
def relationships() do
%{}
end
def url_func(), do: &test_url/3
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment