-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
update go structs for chat to hive feature
- Loading branch information
1 parent
e68cbf3
commit cc0ec36
Showing
2 changed files
with
124 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package db | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"time" | ||
|
||
"gorm.io/gorm" | ||
) | ||
|
||
func (db database) AddChat(chat *Chat) (Chat, error) { | ||
if chat.ID == "" { | ||
return Chat{}, errors.New("chat ID is required") | ||
} | ||
|
||
now := time.Now() | ||
chat.CreatedAt = now | ||
chat.UpdatedAt = now | ||
|
||
if err := db.db.Create(&chat).Error; err != nil { | ||
return Chat{}, fmt.Errorf("failed to create chat: %w", err) | ||
} | ||
|
||
return *chat, nil | ||
} | ||
|
||
func (db database) GetChatByChatID(chatID string) (Chat, error) { | ||
var chat Chat | ||
result := db.db.Where("id = ?", chatID).First(&chat) | ||
|
||
if result.Error != nil { | ||
if errors.Is(result.Error, gorm.ErrRecordNotFound) { | ||
return Chat{}, fmt.Errorf("chat not found") | ||
} | ||
return Chat{}, fmt.Errorf("failed to fetch chat: %w", result.Error) | ||
} | ||
|
||
return chat, nil | ||
} | ||
|
||
func (db database) AddChatMessage(chatMessage *ChatMessage) (ChatMessage, error) { | ||
if chatMessage.ID == "" { | ||
return ChatMessage{}, errors.New("message ID is required") | ||
} | ||
|
||
now := time.Now() | ||
chatMessage.Timestamp = now | ||
|
||
if err := db.db.Create(&chatMessage).Error; err != nil { | ||
return ChatMessage{}, fmt.Errorf("failed to create chat message: %w", err) | ||
} | ||
|
||
return *chatMessage, nil | ||
} | ||
|
||
func (db database) GetChatMessagesForChatID(chatID string) ([]ChatMessage, error) { | ||
var chatMessages []ChatMessage | ||
|
||
result := db.db.Where("chat_id = ?", chatID).Order("timestamp ASC").Find(&chatMessages) | ||
|
||
if result.Error != nil { | ||
return nil, fmt.Errorf("failed to fetch chat messages: %w", result.Error) | ||
} | ||
|
||
if result.RowsAffected == 0 { | ||
return []ChatMessage{}, nil | ||
} | ||
|
||
return chatMessages, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters