Files
mtusi2026lab3/internal/httpapi/postgres_chats.go
T

120 lines
2.3 KiB
Go

package httpapi
import (
"net/http"
"strings"
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
)
type persistentAPI struct{ messenger *service.PersistentMessenger }
func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
actor := userFromContext(r.Context())
if r.URL.Path == "/api/v1/chats" {
switch r.Method {
case http.MethodPost:
var body createChatRequest
if !readJSON(w, r, &body, "title", "member_ids") {
return
}
chat, err := api.messenger.CreateChat(r.Context(),
actor.ID, body.Title, body.MemberIDs,
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, chat)
case http.MethodGet:
limit, cursor, ok := pageParams(w, r)
if !ok {
return
}
page, err := api.messenger.ListChats(r.Context(), actor.ID, limit, cursor)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, page)
default:
requireMethod(w, r, "GET, POST")
}
return
}
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
parts := strings.Split(path, "/")
if len(parts) == 1 && parts[0] != "" {
if !requireMethod(w, r, http.MethodGet) {
return
}
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, chat)
return
}
if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" {
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
return
}
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
if err != nil {
writeAppError(w, err)
return
}
switch r.Method {
case http.MethodPost:
var body createMessageRequest
if !readJSON(w, r, &body, "text") {
return
}
message, err := api.messenger.CreateMessage(r.Context(),
actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"),
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusCreated, message)
case http.MethodGet:
limit, cursor, ok := pageParams(w, r)
if !ok {
return
}
page, err := api.messenger.ListMessages(r.Context(),
actor.ID, chat.ID, limit, cursor,
)
if err != nil {
writeAppError(w, err)
return
}
writeJSON(w, http.StatusOK, page)
default:
requireMethod(w, r, "GET, POST")
}
}