implement sub/unsub topic

This commit is contained in:
Sinh 2021-12-06 11:02:29 +07:00
parent 4c5d75dda6
commit 9970b02567
3 changed files with 70 additions and 6 deletions

View File

@ -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)
}

View File

@ -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"`
}

View File

@ -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
}