Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add put endpoint to update chats #2227

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions db/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,31 @@ func (db database) AddChat(chat *Chat) (Chat, error) {
return *chat, nil
}

func (db database) UpdateChat(chat *Chat) (Chat, error) {
if chat.ID == "" {
return Chat{}, errors.New("chat ID is required")
}

var existingChat Chat
if err := db.db.First(&existingChat, "id = ?", chat.ID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return Chat{}, fmt.Errorf("chat not found")
}
return Chat{}, fmt.Errorf("failed to fetch chat: %w", err)
}

if chat.Title != "" {
existingChat.Title = chat.Title
}
existingChat.UpdatedAt = time.Now()

if err := db.db.Save(&existingChat).Error; err != nil {
return Chat{}, fmt.Errorf("failed to update chat: %w", err)
}

return existingChat, nil
}

func (db database) GetChatByChatID(chatID string) (Chat, error) {
var chat Chat
result := db.db.Where("id = ?", chatID).First(&chat)
Expand Down
1 change: 1 addition & 0 deletions db/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ type Database interface {
GetFeatureBrief(featureUuid string) (string, error)
GetTicketsByPhaseUUID(featureUUID string, phaseUUID string) ([]Tickets, error)
AddChat(chat *Chat) (Chat, error)
UpdateChat(chat *Chat) (Chat, error)
GetChatByChatID(chatID string) (Chat, error)
AddChatMessage(message *ChatMessage) (ChatMessage, error)
UpdateChatMessage(message *ChatMessage) (ChatMessage, error)
Expand Down
56 changes: 56 additions & 0 deletions handlers/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,62 @@ func (ch *ChatHandler) CreateChat(w http.ResponseWriter, r *http.Request) {
})
}

func (ch *ChatHandler) UpdateChat(w http.ResponseWriter, r *http.Request) {
chatID := chi.URLParam(r, "chat_id")
if chatID == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ChatResponse{
Success: false,
Message: "Chat ID is required",
})
return
}

var request struct {
WorkspaceID string `json:"workspaceId"`
Title string `json:"title"`
}

if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ChatResponse{
Success: false,
Message: "Invalid request body",
})
return
}

existingChat, err := ch.db.GetChatByChatID(chatID)
if err != nil {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(ChatResponse{
Success: false,
Message: "Chat not found",
})
return
}

updatedChat := existingChat
updatedChat.Title = request.Title

updatedChat, err = ch.db.UpdateChat(&updatedChat)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ChatResponse{
Success: false,
Message: fmt.Sprintf("Failed to update chat: %v", err),
})
return
}

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(ChatResponse{
Success: true,
Message: "Chat updated successfully",
Data: updatedChat,
})
}

func (ch *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {

var request struct {
Expand Down
151 changes: 151 additions & 0 deletions handlers/chat_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package handlers

import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/go-chi/chi"
"github.com/google/uuid"
"github.com/stakwork/sphinx-tribes/db"
"github.com/stretchr/testify/assert"
)

type Chat struct {
ID string `json:"id"`
WorkspaceID string `json:"workspaceId"`
Title string `json:"title"`
}

func TestUpdateChat(t *testing.T) {
teardownSuite := SetupSuite(t)
defer teardownSuite(t)

chatHandler := NewChatHandler(&http.Client{}, db.TestDB)

t.Run("should successfully update chat when valid data is provided", func(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(chatHandler.UpdateChat)

chat := &db.Chat{
ID: uuid.New().String(),
WorkspaceID: uuid.New().String(),
Title: "Old Title",
}
db.TestDB.AddChat(chat)

requestBody := map[string]string{
"workspaceId": chat.WorkspaceID,
"title": "New Title",
}
bodyBytes, _ := json.Marshal(requestBody)

rctx := chi.NewRouteContext()
rctx.URLParams.Add("chat_id", chat.ID)
req, err := http.NewRequestWithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, rctx),
http.MethodPut,
"/hivechat/"+chat.ID,
bytes.NewReader(bodyBytes),
)
if err != nil {
t.Fatal(err)
}

handler.ServeHTTP(rr, req)

var response ChatResponse
_ = json.Unmarshal(rr.Body.Bytes(), &response)
assert.Equal(t, http.StatusOK, rr.Code)
assert.True(t, response.Success)
assert.Equal(t, "Chat updated successfully", response.Message)
responseData, ok := response.Data.(map[string]interface{})
assert.True(t, ok, "Response data should be a map")
assert.Equal(t, chat.ID, responseData["id"])
assert.Equal(t, "New Title", responseData["title"])
})

t.Run("should return bad request when chat_id is missing", func(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(chatHandler.UpdateChat)

rctx := chi.NewRouteContext()
req, err := http.NewRequestWithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, rctx),
http.MethodPut,
"/hivechat/",
nil,
)
if err != nil {
t.Fatal(err)
}

handler.ServeHTTP(rr, req)

var response ChatResponse
_ = json.Unmarshal(rr.Body.Bytes(), &response)
assert.Equal(t, http.StatusBadRequest, rr.Code)
assert.False(t, response.Success)
assert.Equal(t, "Chat ID is required", response.Message)
})

t.Run("should return bad request when request body is invalid", func(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(chatHandler.UpdateChat)

invalidJson := []byte(`{"title": "New Title"`)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("chat_id", uuid.New().String())
req, err := http.NewRequestWithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, rctx),
http.MethodPut,
"/hivechat/"+uuid.New().String(),
bytes.NewReader(invalidJson),
)
if err != nil {
t.Fatal(err)
}

handler.ServeHTTP(rr, req)

var response ChatResponse
_ = json.Unmarshal(rr.Body.Bytes(), &response)
assert.Equal(t, http.StatusBadRequest, rr.Code)
assert.False(t, response.Success)
assert.Equal(t, "Invalid request body", response.Message)
})

t.Run("should return not found when chat doesn't exist", func(t *testing.T) {
rr := httptest.NewRecorder()
handler := http.HandlerFunc(chatHandler.UpdateChat)

requestBody := map[string]string{
"workspaceId": uuid.New().String(),
"title": "New Title",
}
bodyBytes, _ := json.Marshal(requestBody)

rctx := chi.NewRouteContext()
rctx.URLParams.Add("chat_id", uuid.New().String())
req, err := http.NewRequestWithContext(
context.WithValue(context.Background(), chi.RouteCtxKey, rctx),
http.MethodPut,
"/hivechat/"+uuid.New().String(),
bytes.NewReader(bodyBytes),
)
if err != nil {
t.Fatal(err)
}

handler.ServeHTTP(rr, req)

var response ChatResponse
_ = json.Unmarshal(rr.Body.Bytes(), &response)
assert.Equal(t, http.StatusNotFound, rr.Code)
assert.False(t, response.Success)
assert.Equal(t, "Chat not found", response.Message)
})
}
Loading
Loading