forked from code-corps/code-corps-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_skill_controller.ex
More file actions
65 lines (55 loc) · 1.82 KB
/
user_skill_controller.ex
File metadata and controls
65 lines (55 loc) · 1.82 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
63
64
65
defmodule CodeCorps.UserSkillController do
use CodeCorps.Web, :controller
import CodeCorps.AuthenticationHelpers, only: [authorize: 2, authorized?: 1]
alias CodeCorps.UserSkill
alias JaSerializer.Params
@analytics Application.get_env(:code_corps, :analytics)
plug :load_and_authorize_resource, model: UserSkill, only: [:delete]
plug :scrub_params, "data" when action in [:create]
def index(conn, params) do
user_skills =
UserSkill
|> UserSkill.index_filters(params)
|> preload([:user, :skill])
|> Repo.all
render(conn, "index.json-api", data: user_skills)
end
def create(conn, %{"data" => data = %{"type" => "user-skill"}}) do
changeset = UserSkill.changeset(%UserSkill{}, Params.to_attributes(data))
conn = conn |> authorize(changeset)
if conn |> authorized? do
case Repo.insert(changeset) do
{:ok, user_skill} ->
user_skill = user_skill |> Repo.preload([:user, :skill])
conn
|> @analytics.track(:added, user_skill)
|> put_status(:created)
|> put_resp_header("location", user_skill_path(conn, :show, user_skill))
|> render("show.json-api", data: user_skill)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(CodeCorps.ChangesetView, "error.json-api", changeset: changeset)
end
else
conn
end
end
def show(conn, %{"id" => id}) do
user_skill =
UserSkill
|> preload([:user, :skill])
|> Repo.get!(id)
render(conn, "show.json-api", data: user_skill)
end
def delete(conn, %{"id" => id}) do
user_skill =
UserSkill
|> preload([:user, :skill])
|> Repo.get!(id)
|> Repo.delete!
conn
|> @analytics.track(:removed, user_skill)
|> send_resp(:no_content, "")
end
end