1
votes

I can create my own Plug Module this way http://www.phoenixframework.org/docs/understanding-plug#section-module-plugs

Say, I wanted to check if there's a header in a request and its value and if they were corrent, continue further, if not, terminate the current request and return a certain status and message, probably in json.

However, returning html or json or anything else from a Plug Module isn't allowed, it can only modify a connection structure passed to it on its way to a controller.

Then how would I do that? Should I add a certain key in it instead and then check for it in a controller? But it'd create a lot of repetition, wouldn't it?

   # plug module
   def call(conn, default) do
     if condition1
       assign(conn, :my_key, %{status: :ok, msg: "okkkeey"})
     else
       assign(conn, :my_key, %{status: :error, msg: "we have problems")
   end

   # my_controller
   def action1(conn)
     # check for :my_key and its status
1

1 Answers

4
votes

You can return HTML or JSON from a plug as long as you halt/1 at the end.

   # plug module
   def call(conn, default) do
     if condition1
       assign(conn, :my_key, %{status: :ok, msg: "okkkeey"})
     else
       conn
       |> send_resp(400, "Something wrong")
       |> halt()
   end

If you want to return JSON, you can use Phoenix.Controller.json/2, however you will need to use the full function name as the function is not imported by default.

   def call(conn, default) do
     if condition1
       assign(conn, :my_key, %{status: :ok, msg: "okkkeey"})
     else
       conn
       |> put_status(400)
       |> Phoenix.Controller.json(%{error: "We have problems"})
       |> halt()
   end