forked from mtusi2026/mtusi2026lab2
105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"uuid"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"messenger/internal/domain"
|
|
"messenger/internal/service"
|
|
)
|
|
|
|
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
|
var req createChatRequest
|
|
if err := decodeJSON(w, r, &req); err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
if req.Title == nil || req.MemberIDs == nil {
|
|
h.fail(w, r, badRequest("title and member_ids are required"))
|
|
return
|
|
}
|
|
memberIDs := make([]uuid.UUID, len(*req.MemberIDs))
|
|
for i, s := range *req.MemberIDs {
|
|
id, ok := parseUUID(s)
|
|
if !ok {
|
|
h.fail(w, r, badRequest("member_ids must contain UUIDs"))
|
|
return
|
|
}
|
|
memberIDs[i] = id
|
|
}
|
|
chat, err := h.chats.Create(r.Context(), actor(r), *req.Title, memberIDs)
|
|
if err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, toChatResponse(chat))
|
|
}
|
|
|
|
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
|
limit, cursor, err := pageParams(r)
|
|
if err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
page, err := h.chats.List(r.Context(), actor(r), cursor, limit)
|
|
if err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, toPageResponse(page, toChatResponse))
|
|
}
|
|
|
|
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
|
chatID, err := chatIDParam(r)
|
|
if err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
chat, err := h.chats.Get(r.Context(), actor(r), chatID)
|
|
if err != nil {
|
|
h.fail(w, r, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, toChatResponse(chat))
|
|
}
|
|
|
|
func chatIDParam(r *http.Request) (uuid.UUID, error) {
|
|
id, ok := parseUUID(chi.URLParam(r, "chat_id"))
|
|
if !ok {
|
|
return uuid.UUID{}, badRequest("chat_id must be a UUID")
|
|
}
|
|
return id, nil
|
|
}
|
|
|
|
func parseUUID(s string) (uuid.UUID, bool) {
|
|
if len(s) != 36 {
|
|
return uuid.UUID{}, false
|
|
}
|
|
id, err := uuid.Parse(s)
|
|
return id, err == nil
|
|
}
|
|
|
|
func pageParams(r *http.Request) (int, *domain.Cursor, error) {
|
|
q := r.URL.Query()
|
|
limit := service.DefaultLimit
|
|
if q.Has("limit") {
|
|
n, err := strconv.Atoi(q.Get("limit"))
|
|
if err != nil {
|
|
return 0, nil, badRequest("limit must be an integer")
|
|
}
|
|
limit = n
|
|
}
|
|
var cursor *domain.Cursor
|
|
if q.Has("cursor") {
|
|
c, ok := decodeCursor(q.Get("cursor"))
|
|
if !ok {
|
|
return 0, nil, badRequest("invalid cursor")
|
|
}
|
|
cursor = &c
|
|
}
|
|
return limit, cursor, nil
|
|
}
|