diff --git a/example/main.go b/example/main.go index fb1cd1f..40d7921 100644 --- a/example/main.go +++ b/example/main.go @@ -55,4 +55,9 @@ func main() { Category: "order", }) fmt.Println("Count: 2", total, err) + + err = c.Subscribe("test", []string{ + "eX1gEc7WokSHh-zJ3WR5Hn:APA91bFZDuzkjjFFL6TNpMg0ot93a0wsypWi4aCdm7M2x6AihgjS_QWsbKSFCT4hNhv_d8wKGy-DG6_3e8OlwPiWiJB4R33xLbbUekgxKcfCiiFooIC1E1OE3XWkvUtn4egn8aLG5jqv", + }) + fmt.Println("Subscribe err: ", err) } diff --git a/model.go b/model.go index 7e80094..0e6cbba 100644 --- a/model.go +++ b/model.go @@ -75,11 +75,6 @@ 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"` @@ -101,3 +96,19 @@ type countUnread struct { User string `json:"user"` Category string `json:"category"` } + +// CommonError ... +type CommonError struct { + Error string `json:"error"` +} + +// Subscribe ... +type Subscribe struct { + Tokens []string `json:"tokens"` + Topic string `json:"topic"` +} + +type subscribe struct { + Subscribe + APIKey string `json:"apiKey"` +} diff --git a/notification.go b/notification.go index f0517d6..8722bdb 100644 --- a/notification.go +++ b/notification.go @@ -18,6 +18,8 @@ const ( SubjectGetNotification = "get_notification" SubjectReadNotification = "read_notification" SubjectCountUnreadNotification = "count_unread_notification" + SubjectSubscribeTopic = "subscribe_topic" + SubjectUnsubscribeTopic = "unsubscribe_topic" ) // Client ... @@ -137,7 +139,53 @@ func (c *Client) Read(notificationID string) error { if err != nil { return err } - var res ReadResponse + var res CommonError + if err := json.Unmarshal(msg.Data, &res); err != nil { + return err + } + if res.Error != "" { + err = errors.New(res.Error) + } + return err +} + +// Subscribe tokens to topic +func (c *Client) Subscribe(topic string, tokens []string) error { + p := subscribe{ + Subscribe: Subscribe{ + Tokens: tokens, + Topic: topic, + }, + APIKey: c.Config.APIKey, + } + msg, err := c.natsServer.Request(SubjectSubscribeTopic, toBytes(p)) + if err != nil { + return err + } + var res CommonError + if err := json.Unmarshal(msg.Data, &res); err != nil { + return err + } + if res.Error != "" { + err = errors.New(res.Error) + } + return err +} + +// Unsubscribe tokens from topic +func (c *Client) Unsubscribe(topic string, tokens []string) error { + p := subscribe{ + Subscribe: Subscribe{ + Tokens: tokens, + Topic: topic, + }, + APIKey: c.Config.APIKey, + } + msg, err := c.natsServer.Request(SubjectUnsubscribeTopic, toBytes(p)) + if err != nil { + return err + } + var res CommonError if err := json.Unmarshal(msg.Data, &res); err != nil { return err }