forked from code-corps/code-corps-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorganization_controller.ex
More file actions
62 lines (53 loc) · 2.12 KB
/
organization_controller.ex
File metadata and controls
62 lines (53 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
defmodule CodeCorps.OrganizationController do
use CodeCorps.Web, :controller
import CodeCorps.Organization, only: [changeset: 2]
alias CodeCorps.Organization
alias JaSerializer.Params
plug :load_and_authorize_resource, model: Organization, only: [:create, :update]
plug :scrub_params, "data" when action in [:create, :update]
def index(conn, params) do
organizations =
Organization
|> Organization.index_filters(params)
|> preload([:organization_memberships, :projects, :slugged_route])
|> Repo.all
render(conn, "index.json-api", data: organizations)
end
def create(conn, %{"data" => data = %{"type" => "organization", "attributes" => _organization_params}}) do
changeset = Organization.create_changeset(%Organization{}, Params.to_attributes(data))
case Repo.insert(changeset) do
{:ok, organization} ->
organization = Repo.preload(organization, [:members, :projects, :slugged_route])
conn
|> put_status(:created)
|> put_resp_header("location", organization_path(conn, :show, organization))
|> render("show.json-api", data: organization)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(CodeCorps.ChangesetView, "error.json-api", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
organization =
Organization
|> preload([:organization_memberships, :projects, :slugged_route])
|> Repo.get!(id)
render(conn, "show.json-api", data: organization)
end
def update(conn, %{"id" => id, "data" => data = %{"type" => "organization", "attributes" => _organization_params}}) do
changeset =
Organization
|> preload([:organization_memberships, :projects, :slugged_route])
|> Repo.get!(id)
|> changeset(Params.to_attributes(data))
case Repo.update(changeset) do
{:ok, organization} ->
render(conn, "show.json-api", data: organization)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(CodeCorps.ChangesetView, "error.json-api", changeset: changeset)
end
end
end