-
Notifications
You must be signed in to change notification settings - Fork 3
/
client_base_notifications.go
97 lines (88 loc) · 2.46 KB
/
client_base_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
package websocket
import (
"context"
"encoding/json"
"fmt"
"reflect"
"github.com/cryptomkt/cryptomkt-go/v3/args"
"github.com/cryptomkt/cryptomkt-go/v3/models"
)
type parseNotificationFnType func([]byte)
func (client *clientBase) doRequest(
ctx context.Context,
method string,
arguments []args.Argument,
requiredArguments []string,
model interface{},
) error {
return client.doRequestOfNNotifications(ctx, method, arguments, requiredArguments, unmarshalDataToModel(model), "")
}
func unmarshalDataToModel(model interface{}) parseNotificationFnType {
return func(data []byte) { json.Unmarshal(data, model) }
}
func (client *clientBase) doRequestOfNNotifications(
ctx context.Context,
method string,
arguments []args.Argument,
requiredArguments []string,
parseNotificationFn parseNotificationFnType,
nNotificationsParam string,
) error {
params, err := args.BuildParams(arguments, requiredArguments...)
if err != nil {
return err
}
nNotifications := getNOfNotifications(params, nNotificationsParam)
if !client.wsManager.isOpen {
return fmt.Errorf("CryptomarketSDKError: websocket connection is closed")
}
ch := make(chan []byte, 1)
id := client.chanCache.saveCh(ch, nNotifications)
notification := wsNotification{
ID: id,
Method: method,
Params: params,
}
data, err := json.Marshal(notification)
if err != nil {
client.chanCache.closeAndRemoveCh(id)
return fmt.Errorf("CryptomarketSDKError: invalid notification: %v", err)
}
client.sendRequest(data)
return client.handleResponse(ctx, id, ch, nNotifications, parseNotificationFn)
}
func (client *clientBase) sendRequest(data []byte) {
client.wsManager.snd <- data
}
func getNOfNotifications(params map[string]interface{}, nNotificationsParam string) int {
if len(nNotificationsParam) == 0 {
return 1
}
param, ok := params[nNotificationsParam]
if !ok {
return 1
}
if reflect.TypeOf(param).Kind() != reflect.Slice {
return 1
}
return reflect.ValueOf(param).Len()
}
func (client *clientBase) handleResponse(ctx context.Context, id int64, ch chan []byte, nNotifications int, updateModelAggFn parseNotificationFnType) error {
for i := 0; i < nNotifications; i++ {
select {
case <-ctx.Done():
client.chanCache.closeAndRemoveCh(id)
return ctx.Err()
case data := <-ch:
var resp struct {
Error *models.APIError
}
json.Unmarshal(data, &resp)
if resp.Error != nil {
return fmt.Errorf("CryptomarketAPIError: %v", resp.Error)
}
updateModelAggFn(data)
}
}
return nil
}