-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifications.go
125 lines (111 loc) · 2.13 KB
/
notifications.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package sn
import (
"encoding/json"
"fmt"
"time"
)
type Notification struct {
Id int `json:"id,string"`
Type string `json:"__typename"`
Item Item `json:"item"`
}
type NotificationsCursor struct {
LastChecked time.Time `json:"lastChecked"`
Cursor string `json:"cursor"`
Notifications []Notification `json:"notifications"`
}
type NotificationsResponse struct {
Errors []GqlError `json:"errors"`
Data struct {
Notifications NotificationsCursor `json:"notifications"`
} `json:"data"`
}
func (c *Client) Notifications() (*NotificationsCursor, error) {
body := GqlBody{
Query: `
fragment ItemFields on Item {
id
user {
id
name
}
parentId
createdAt
deletedAt
title
text
}
query notifications {
notifications {
lastChecked
cursor
notifications {
__typename
... on Reply {
id
item {
...ItemFields
}
}
... on Mention {
id
item {
...ItemFields
}
}
}
}
}
`,
Variables: map[string]interface{}{},
}
resp, err := c.callApi(body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var respBody NotificationsResponse
err = json.NewDecoder(resp.Body).Decode(&respBody)
if err != nil {
err = fmt.Errorf("error decoding notifications: %w", err)
return nil, err
}
err = c.checkForErrors(respBody.Errors)
if err != nil {
return nil, err
}
return &respBody.Data.Notifications, nil
}
func (c *Client) Mentions() ([]Notification, error) {
return c.filterNotifications(
func(n Notification) bool {
return n.Type == "Mention"
},
)
}
func (c *Client) Replies() ([]Notification, error) {
return c.filterNotifications(
func(n Notification) bool {
return n.Type == "Reply"
},
)
}
func (c *Client) filterNotifications(f func(Notification) bool) ([]Notification, error) {
var (
n *NotificationsCursor
err error
)
if n, err = c.Notifications(); err != nil {
return nil, err
}
return filter(n.Notifications, f), nil
}
func filter[T any](s []T, f func(T) bool) []T {
var r []T
for _, v := range s {
if f(v) {
r = append(r, v)
}
}
return r
}