Return statement in Elixir

后端 未结 8 1378
野趣味
野趣味 2020-12-14 00:38

I need a function with some kind of a step-by-step logic and I wonder how I can make one. Let\'s take a log in process on a site as an example, so I need the following logic

8条回答
  •  醉梦人生
    2020-12-14 01:33

    This is exactly the situation I'd use elixir pipes library

    defmodule Module do
      use Phoenix.Controller
      use Pipe
    
      plug :action
    
      def action(conn, params) do
        start_val = {:ok, conn, params}
        pipe_matching {:ok, _, _},
          start_val
            |> email_present
            |> email_length
            |> do_action
      end
    
      defp do_action({_, conn, params}) do
        # do stuff with all input being valid
      end
    
      defp email_present({:ok, _conn, %{ "email" => _email }} = input) do
        input
      end
      defp email_present({:ok, conn, params}) do
        bad_request(conn, "email is a required field")
      end
    
      defp email_length({:ok, _conn, %{ "email" => email }} = input) do
        case String.length(email) > 5 do
          true -> input
          false -> bad_request(conn, "email field is too short")
      end
    
      defp bad_request(conn, msg) do
        conn 
          |> put_status(:bad_request) 
          |> json( %{ error: msg } )
      end
    end
    

    Note, this produces long pipes a lot of times and it is addictive :-)

    Pipes library has more ways to keep piping than pattern matching I used above. Have a look elixir-pipes at the examples and tests.

    Also, if validation becomes a common theme in your code maybe it is time to check Ecto's changeset validations or Vex another library that does nothing else but validate your input.

提交回复
热议问题