tsk-8: Create Message endpoint (#15)

Closes #8

Reviewed-on: phoenix/textsender-api#15
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
phoenix
2025-11-05 19:37:49 +00:00
committed by phoenix
parent 2045465111
commit 507eb9eb09
9 changed files with 230 additions and 3 deletions
+72
View File
@@ -0,0 +1,72 @@
package handler
import (
"fmt"
"net/http"
"github.com/google/uuid"
"git.kundeng.us/phoenix/textsender-api/internal/store"
"git.kundeng.us/phoenix/textsender-models/pkg/message"
)
type RequestAddMessage struct {
Content string `json:"content"`
UserId uuid.UUID `json:"user_id"`
}
type AddMessageResponse struct {
Message string `json:"message"`
Data []message.Message `json:"data"`
}
type MessageHandler struct {
MessageStore store.MessageStore
}
func NewMessageHandler(str store.MessageStore) *MessageHandler {
return &MessageHandler{MessageStore: str}
}
func (m *MessageHandler) AddMessage(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req RequestAddMessage
if err := ExtractFromRequest(r, &req); err != nil {
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
}
defer r.Body.Close()
newMessage := message.Message{Content: req.Content, UserId: req.UserId}
var statusCode int
var resp AddMessageResponse
ctx := r.Context()
if exists, err := m.MessageStore.MessageExists(ctx, &newMessage); err != nil {
fmt.Println("Error: ", err)
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
if exists {
statusCode = http.StatusBadRequest
resp.Message = "Cannot create message"
} else {
if err = m.MessageStore.CreateMessage(ctx, &newMessage); err != nil {
fmt.Println("Error:", err)
statusCode = http.StatusInternalServerError
resp.Message = err.Error()
} else {
statusCode = http.StatusCreated
resp.Message = "Message created"
resp.Data = append(resp.Data, newMessage)
}
}
}
RespondWithJSON(w, statusCode, &resp)
}