From 20b0bccbc24af26431739230237ff2834c5ae581 Mon Sep 17 00:00:00 2001 From: Sinh Date: Fri, 3 Dec 2021 11:25:50 +0700 Subject: [PATCH] count unread and read notification --- model.go | 10 ++++++++++ notification.go | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/model.go b/model.go index c6246d1..1eb9fd7 100644 --- a/model.go +++ b/model.go @@ -75,6 +75,11 @@ type Read struct { ID string `json:"id"` } +// ReadResponse ... +type ReadResponse struct { + Error string `json:"error"` +} + type read struct { APIKey string `json:"apiKey"` ID string `json:"id"` @@ -86,6 +91,11 @@ type CountUnread struct { Category string `json:"category"` } +// CountUnreadResponse ... +type CountUnreadResponse struct { + Total int64 `json:"total"` +} + type countUnread struct { APIKey string `json:"apiKey"` User string `json:"user"` diff --git a/notification.go b/notification.go index f06a5c4..9e19f1d 100644 --- a/notification.go +++ b/notification.go @@ -82,7 +82,7 @@ func (c *Client) Query(q Query) (ListNotificationResponse, error) { Page: q.Page, Limit: q.Limit, } - msg, err := c.natsServer.Request(SubjectPushNotification, toBytes(p)) + msg, err := c.natsServer.Request(SubjectGetNotification, toBytes(p)) if err != nil { return ListNotificationResponse{}, err } @@ -93,6 +93,44 @@ func (c *Client) Query(q Query) (ListNotificationResponse, error) { return res, nil } +// CountUnread count total unread notification +func (c *Client) CountUnread(q CountUnread) (int64, error) { + p := countUnread{ + APIKey: c.Config.APIKey, + User: q.User, + Category: q.Category, + } + msg, err := c.natsServer.Request(SubjectCountUnreadNotification, toBytes(p)) + if err != nil { + return 0, err + } + var res CountUnreadResponse + if err := json.Unmarshal(msg.Data, &res); err != nil { + return 0, err + } + return res.Total, nil +} + +// Read mark notification as read +func (c *Client) Read(notificationID string) error { + p := read{ + APIKey: c.Config.APIKey, + ID: notificationID, + } + msg, err := c.natsServer.Request(SubjectReadNotification, toBytes(p)) + if err != nil { + return err + } + var res ReadResponse + if err := json.Unmarshal(msg.Data, &res); err != nil { + return err + } + if res.Error != "" { + err = errors.New(res.Error) + } + return err +} + func toBytes(data interface{}) []byte { b, _ := json.Marshal(data) return b