|
1 | 1 | defmodule CodeCorpsWeb.ProjectCategoryController do |
2 | 2 | use CodeCorpsWeb, :controller |
3 | | - use JaResource |
4 | 3 |
|
5 | | - alias CodeCorps.ProjectCategory |
| 4 | + alias CodeCorps.{ProjectCategory, User, Helpers.Query} |
6 | 5 |
|
7 | | - import CodeCorps.Helpers.Query, only: [id_filter: 2] |
| 6 | + action_fallback CodeCorpsWeb.FallbackController |
| 7 | + plug CodeCorpsWeb.Plug.DataToAttributes |
| 8 | + plug CodeCorpsWeb.Plug.IdsToIntegers |
8 | 9 |
|
9 | | - plug :load_resource, model: ProjectCategory, only: [:show], preload: [:project, :category] |
10 | | - plug :load_and_authorize_changeset, model: ProjectCategory, only: [:create] |
11 | | - plug :load_and_authorize_resource, model: ProjectCategory, only: [:delete] |
12 | | - plug JaResource |
| 10 | + @spec index(Conn.t, map) :: Conn.t |
| 11 | + def index(%Conn{} = conn, %{} = params) do |
| 12 | + with project_categories <- ProjectCategory |> Query.id_filter(params) |> Repo.all do |
| 13 | + conn |> render("index.json-api", data: project_categories) |
| 14 | + end |
| 15 | + end |
13 | 16 |
|
14 | | - @spec model :: module |
15 | | - def model, do: CodeCorps.ProjectCategory |
| 17 | + @spec show(Conn.t, map) :: Conn.t |
| 18 | + def show(%Conn{} = conn, %{"id" => id}) do |
| 19 | + with %ProjectCategory{} = project_category <- ProjectCategory |> Repo.get(id) do |
| 20 | + conn |> render("show.json-api", data: project_category) |
| 21 | + end |
| 22 | + end |
16 | 23 |
|
17 | | - def filter(_conn, query, "id", id_list) do |
18 | | - query |> id_filter(id_list) |
| 24 | + @spec create(Plug.Conn.t, map) :: Conn.t |
| 25 | + def create(%Conn{} = conn, %{} = params) do |
| 26 | + with %User{} = current_user <- conn |> Guardian.Plug.current_resource, |
| 27 | + {:ok, :authorized} <- current_user |> Policy.authorize(:create, %ProjectCategory{}, params), |
| 28 | + {:ok, %ProjectCategory{} = project_category} <- %ProjectCategory{} |> ProjectCategory.create_changeset(params) |> Repo.insert do |
| 29 | + conn |> put_status(:created) |> render("show.json-api", data: project_category) |
| 30 | + end |
19 | 31 | end |
20 | 32 |
|
21 | | - def handle_create(_conn, attributes) do |
22 | | - %ProjectCategory{} |> ProjectCategory.create_changeset(attributes) |
| 33 | + @spec delete(Conn.t, map) :: Conn.t |
| 34 | + def delete(%Conn{} = conn, %{"id" => id} = _params) do |
| 35 | + with %ProjectCategory{} = project_category <- ProjectCategory |> Repo.get(id), |
| 36 | + %User{} = current_user <- conn |> Guardian.Plug.current_resource, |
| 37 | + {:ok, :authorized} <- current_user |> Policy.authorize(:delete, project_category), |
| 38 | + {:ok, %ProjectCategory{} = _project_category} <- project_category |> Repo.delete |
| 39 | + do |
| 40 | + conn |> Conn.assign(:project_category, project_category) |> send_resp(:no_content, "") |
| 41 | + end |
23 | 42 | end |
24 | 43 | end |
0 commit comments