Partially required request body params

I have a create function that takes conn and params as an argument and in the params, there can be 3 possible values where 2 of them are non-mandatory and 1 is required.

 def create(conn, %{}) do
    conn 
    |> put_status(:bad_request)
    |> json(%{"message" => "tenant_id is required"})
  end
def create(conn, route_params \\ %{"tenant_id" => tenant_id}) do
      with {:ok, %Route{} = route} <- Shortner.create_route(route_params) do
        conn
        |> put_status(:created)
        |> put_resp_header("location", route_path(conn, :show, route))
        |> render("show.json", route: route)
      end
  end

how can create the create function when tenant_id is missing I throw an error else just proceed as it is.

Note: I have introduced this new field just now as a requirement earlier we just had name & prefix and both were non-mandatory.

Thanks

If I am understanding you correctly you need to swap the order of the functions and remove the default value:

def create(conn, %{"tenant_id" => tenant_id} = route_params) do
  with {:ok, %Route{} = route} <- Shortner.create_route(route_params) do
    conn
    |> put_status(:created)
    |> put_resp_header("location", route_path(conn, :show, route))
    |> render("show.json", route: route)
  end
end

def create(conn, %{}) do
  conn 
  |> put_status(:bad_request)
  |> json(%{"message" => "tenant_id is required"})
end
2 Likes