elixir-maru / maru

Elixir RESTful Framework
https://maru.readme.io
BSD 3-Clause "New" or "Revised" License
1.32k stars 84 forks source link

How do I run a plug function in a route_param scope? #56

Closed feymartynov closed 7 years ago

feymartynov commented 7 years ago
defmodule MyApp.Users do
  use Maru.Router

  alias MyApp.{Repo, User}

  defp find_user(conn, _opts) do
    case Repo.get(User, conn.params.id) do
      nil -> conn |> put_status(404) |> |> json(%{error: "Not found"}) |> halt
      user -> conn |> assign(:user, user)
    end
  end

  namespace :users do
    route_param :id do
      plug :find_user

      get do
        conn |> json(conn.assigns.user)
      end

      put do
        case conn.assigns.user |> User.changeset(params) |> Repo.update do
          {:ok, user} -> conn |> json(user)
          {:error, changeset} -> conn |> json(%{errors: changeset.errors})
        end
      end
    end
  end
end

The above Phoenix-style code doesn't work but I hope you get the idea what I'm trying to do. What's the correct way?

falood commented 7 years ago

@feymartynov I'm sorry for the delay, I have had a trip last week. you can use plug with maru like this, it's the correct way! but maru don't support function-plug very well if you have deep-mount routes, so my suggestion is using module-plug.

feymartynov commented 7 years ago

Ok. Thanks for the clarification!