#How to refactor nested conditions

8 messages · Page 1 of 1 (latest)

ocean gale
#

I wanna know what are some good practices when it comes to nested conditions. I believe the below is too nested and could be improved but have no idea what are the options in Elixir. All tips appreciated.

def payment_tracking(conn, params) do
  case params do
    %{type: "completed", data: %{object: %{metadata: %{custom_id: id}}}} ->
      if is_nil(id) do
        conn |> put_status(400)
      else
        result =
          case WebApi.Account.get_user_by_custom_id(id) do
            nil  -> %WebApi.Account.User{custom_id: discord_id}
            user -> user
          end
          |> WebApi.Account.User.changeset(%{})
          |> WebApi.Repo.insert_or_update

        case result do
          {:ok, user} ->
            now = DateTime.utc_now()
            current_license = WebApi.Account.get_current_license(user.id)

            license = WebApi.Account.License |> Ecto.Query.first |> WebApi.Repo.one

            {activation_date, minutes_total} =
              case current_license do
                nil ->
                  
                _ ->
                  
              end
          {:error, changeset} ->

        end
      end
    _ -> conn |> put_status(200)
  end
end
#

How to refactor nested conditions

warm lark
#

the with statement is meant for cleaning up nested cases

#

also, maybe move some of the pieces into private functions

#

you should also not be using Repo directly from inside a controller like this, those operations should be moved to "business logic context" modules

ocean gale
#

Thanks. I already saw use of with somewhere. Regarding repo. Basically I should move it into Account module like some other functions f.e get_current_license?

warm lark
#

yes, exactly