commit 2dc180dce8750f4e606661eeafcfa73d044a4824
parent 87a6f163d9c1cbf081075e9f114c712fa75eb2df
Author: n0tr1v <n0tr1v@protonmail.com>
Date: Sun, 15 Jan 2023 17:28:17 -0800
simplify code, reduce sql queries
Diffstat:
2 files changed, 11 insertions(+), 2 deletions(-)
diff --git a/pkg/database/tableChatRooms.go b/pkg/database/tableChatRooms.go
@@ -192,6 +192,8 @@ WHERE owner_user_id IS NOT NULL
AND chat_rooms.created_at < date('now', '-1 Day');`)
}
+// ChatReadRecord use to keep track of last message read (loaded) in a room, for rooms new message indicator.
+// ie: a room you're not currently in, changes color if new messages are posted in it.
type ChatReadRecord struct {
UserID UserID
RoomID RoomID
@@ -203,3 +205,11 @@ func (r *ChatReadRecord) DoSave() {
logrus.Error(err)
}
}
+
+func UpdateChatReadRecord(userID UserID, roomID RoomID) {
+ now := time.Now()
+ res := DB.Table("chat_read_records").Where("user_id = ? AND room_id = ?", userID, roomID).Update("read_at", now)
+ if res.RowsAffected == 0 {
+ DB.Create(ChatReadRecord{UserID: userID, RoomID: roomID, ReadAt: now})
+ }
+}
diff --git a/pkg/web/handlers/api/v1/handlers.go b/pkg/web/handlers/api/v1/handlers.go
@@ -118,8 +118,7 @@ func ChatMessagesHandler(c echo.Context) error {
}
// Update read record
- database.DB.Create(database.ChatReadRecord{UserID: authUser.ID, RoomID: room.ID})
- database.DB.Table("chat_read_records").Where("user_id = ? AND room_id = ?", authUser.ID, room.ID).Update("read_at", time.Now())
+ database.UpdateChatReadRecord(authUser.ID, room.ID)
var data chatMessagesData