I’m building a multiplayer game using Phoenix LiveView. A user joins a game by giving its name as the id on the url: e.g. “/game-room-name”. User joins an existing game with that name of one is created. So far so good.
But I want to sanitize the game name, so when user goes to “/My%20New%20Game”, they are redirected instead to “/my-new-game”.
Correct me if I’m wrong, but I can’t do that in the liveview mount. Can I do it in a Plug instead? Or is that a better way?
Thanks!
Actually, nevermind, I see I can do this with a plug and redirect. Here’s how I wrote my plug:
defmodule ChukinasWeb.Plugs.SanitizeRoomName do
# TODO how to add documentation?
alias Phoenix.Controller
alias Plug.Conn
def init(opts) do
opts
end
def call(%{:path_params => %{"room_name" => room_name}} = conn, _opts) do
room_slug = slugify(room_name)
if room_slug != room_name do
path =
conn.request_path
|> URI.decode()
|> String.replace(room_name, room_slug)
conn
|> Controller.redirect(to: path)
|> Conn.halt()
else
conn
end
end
def call(conn, _opts) do
conn
end
def slugify(string) do
string
|> String.downcase()
|> String.replace(~r/[^\w-]+/u, "-")
end
end
1 Like