Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions lib/my_app_web/live/queries_live.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
defmodule MyAppWeb.QueriesLive do
use MyAppWeb, :live_view

alias MyApp.Repo

@impl true
def render(assigns) do
~H"""
<div class="mx-auto max-w-2xl p-8">
<h1 class="text-3xl font-bold mb-8">Database Queries</h1>

<div class="space-y-8">
<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title">now()</h2>
<p class="text-lg font-mono"><%= @now %></p>
</div>
</div>

<div class="card bg-base-100 shadow-xl">
<div class="card-body">
<h2 class="card-title">random()</h2>
<.async_result assign={@random}>
<div id="random_value" :if={rn = @random.ok? && @random.result}>{rn}</div>
<:loading>
<div class="loading loading-spinner loading-md"></div>
</:loading>
<:failed :let={reason}>
<p class="text-error">Failed to load: <%= reason %></p>
</:failed>
</.async_result>
</div>
</div>
</div>
</div>
"""
end

@impl true
def mount(_params, _session, socket) do
{:ok, results} = Repo.query("SELECT now();")
[[now]] = results.rows

socket =
socket
|> assign(:now, now)
|> assign_async(:random, fn -> fetch_random_number() end)

{:ok, socket}
end


defp fetch_random_number() do
# Maybe pretend this is slow
Process.sleep(query_delay())
{:ok, results} = Repo.query("SELECT random();")
[[random]] = results.rows
{:ok, %{random: random}}
end

defp query_delay do
with delay_str <- System.get_env("QUERY_DELAY"),
true <- is_binary(delay_str),
{delay, ""} <- Integer.parse(delay_str) do
delay
else
_ -> 0
end
end
end
5 changes: 5 additions & 0 deletions lib/my_app_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ defmodule MyAppWeb.Router do
pipe_through :browser

get "/", PageController, :home

live_session :default,
on_mount: @common_on_mount_hooks do
live "/queries", QueriesLive, :index
end
end

# Other scopes may use custom stacks.
Expand Down
2 changes: 2 additions & 0 deletions test/features/register_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,7 @@ defmodule Features.RegisterTest do
|> visit(~p"/users/settings")
|> assert_has(".phx-connected")
|> assert_has("h1", text: "Settings")
|> visit(~p"/queries")
|> assert_has("h1", text: "Database Queries")
end
end