feat: add context methods to mutate rooms

Also, improve user input validation.
This commit is contained in:
João Paulo Dubas 2024-10-16 00:31:12 +00:00
parent c6ee2bbf0b
commit 32350431f8
Signed by: joao.dubas
SSH Key Fingerprint: SHA256:V1mixgOGRc/YMhGx/DNkOSmJxgA2vHNrDZEk3wt/kOA
2 changed files with 18 additions and 1 deletions

View File

@ -8,6 +8,18 @@ defmodule Slax.Chat do
alias Slax.Chat.Room
alias Slax.Repo
def create_room(attrs) do
%Room{}
|> Room.changeset(attrs)
|> Repo.insert()
end
def update_room(%Room{} = room, attrs) do
room
|> Room.changeset(attrs)
|> Repo.update()
end
def get_first_room! do
query = from(r in Room, limit: 1, order_by: [asc: :name])
Repo.one!(query)

View File

@ -13,6 +13,11 @@ defmodule Slax.Chat.Room do
def changeset(room, attrs) do
room
|> cast(attrs, [:name, :topic])
|> validate_required([:name, :topic])
|> validate_required([:name])
|> validate_length(:name, max: 80)
|> validate_format(:name, ~r/\A[a-z0-9-]+\z/,
message: "can only contain lowercase letters, numbers, and dashes"
)
|> validate_length(:topic, max: 200)
end
end