From fcd3b56f89bd492805bfeeeabac6b5422547a763 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Wed, 1 Jan 2025 11:16:54 +0800 Subject: [PATCH] :sparkles: Mark all notification as read api --- pkg/internal/http/api/index.go | 1 + pkg/internal/http/api/notifications_api.go | 25 +++++++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/pkg/internal/http/api/index.go b/pkg/internal/http/api/index.go index 586a997..1be11d1 100644 --- a/pkg/internal/http/api/index.go +++ b/pkg/internal/http/api/index.go @@ -25,6 +25,7 @@ func MapAPIs(app *fiber.App, baseURL string) { notify.Post("/subscription", addNotifySubscriber) notify.Delete("/subscription/:deviceId", removeNotifySubscriber) notify.Put("/read", markNotificationReadBatch) + notify.Put("/read/all", markNotificationAllRead) notify.Put("/read/:notificationId", markNotificationRead) } diff --git a/pkg/internal/http/api/notifications_api.go b/pkg/internal/http/api/notifications_api.go index de7aebf..91b33d8 100644 --- a/pkg/internal/http/api/notifications_api.go +++ b/pkg/internal/http/api/notifications_api.go @@ -1,14 +1,15 @@ package api import ( + "strconv" + "time" + "git.solsynth.dev/hypernet/passport/pkg/authkit/models" "git.solsynth.dev/hypernet/passport/pkg/internal/database" "git.solsynth.dev/hypernet/passport/pkg/internal/http/exts" "git.solsynth.dev/hypernet/passport/pkg/internal/services" "github.com/gofiber/fiber/v2" "github.com/samber/lo" - "strconv" - "time" ) func getNotifications(c *fiber.Ctx) error { @@ -110,11 +111,29 @@ func markNotificationReadBatch(c *fiber.Ctx) error { Updates(&models.Notification{ReadAt: lo.ToPtr(time.Now())}).Error; err != nil { return fiber.NewError(fiber.StatusInternalServerError, err.Error()) } else { - services.AddEvent(user.ID, "notifications.markAll.read", strconv.Itoa(int(user.ID)), c.IP(), c.Get(fiber.HeaderUserAgent)) + services.AddEvent(user.ID, "notifications.markBatch.read", strconv.Itoa(int(user.ID)), c.IP(), c.Get(fiber.HeaderUserAgent)) return c.SendStatus(fiber.StatusOK) } } +func markNotificationAllRead(c *fiber.Ctx) error { + if err := exts.EnsureAuthenticated(c); err != nil { + return err + } + user := c.Locals("user").(models.Account) + + if tx := database.C.Model(&models.Notification{}). + Where("account_id = ? AND read_at IS NULL", user.ID). + Updates(&models.Notification{ReadAt: lo.ToPtr(time.Now())}); tx.Error != nil { + return fiber.NewError(fiber.StatusInternalServerError, tx.Error.Error()) + } else { + services.AddEvent(user.ID, "notifications.markAll.read", strconv.Itoa(int(user.ID)), c.IP(), c.Get(fiber.HeaderUserAgent)) + return c.JSON(fiber.Map{ + "count": tx.RowsAffected, + }) + } +} + func getNotifySubscriber(c *fiber.Ctx) error { if err := exts.EnsureAuthenticated(c); err != nil { return err