-
Notifications
You must be signed in to change notification settings - Fork 14
/
hook.go
127 lines (110 loc) · 2.31 KB
/
hook.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
126
127
package mango
import (
"encoding/json"
"fmt"
)
func (m *MangoPay) NewHook(eventType EventType, url string) (*Hook, error) {
hook := &Hook{
EventType: eventType,
Url: url,
service: m,
}
return hook, nil
}
type Hook struct {
ProcessIdent
Url string
EventType EventType
Status string
Validity string
service *MangoPay
}
func (h *Hook) String() string {
return struct2string(h)
}
func (h *Hook) Save() error {
var action mangoAction
if h.Id == "" {
action = actionCreateHook
} else {
action = actionUpdateHook
}
data := JsonObject{}
j, err := json.Marshal(h)
if err != nil {
return err
}
if err := json.Unmarshal(j, &data); err != nil {
return err
}
// Fields not allowed when creating an object.
if action == actionCreateWallet {
delete(data, "Id")
}
delete(data, "Status")
delete(data, "Validity")
if action == actionUpdateHook {
// Delete empty values so that existing ones don't get
// overwritten with empty values.
for k, v := range data {
switch v.(type) {
case string:
if v.(string) == "" {
delete(data, k)
}
case int:
if v.(int) == 0 {
delete(data, k)
}
}
}
}
hook, err := h.service.anyRequest(new(Hook), action, data)
if err != nil {
return err
}
serv := h.service
*h = *(hook.(*Hook))
h.service = serv
return nil
}
func (m *MangoPay) Hook(id string) (*Hook, error) {
h, err := m.anyRequest(new(Hook), actionFetchHook, JsonObject{"Id": id})
if err != nil {
return nil, err
}
hook := h.(*Hook)
hook.service = m
return hook, nil
}
// HookByEventType returns the only hook for given event type.
// see https://docs.mangopay.com/endpoints/v2.01/hooks#e247_create-a-hook
func (m *MangoPay) HookByEventType(eventType EventType) (*Hook, error) {
hooks, err := m.Hooks()
if err != nil {
return nil, err
}
var result *Hook
for _, hook := range hooks {
if hook.EventType == eventType {
result = hook
break
}
}
if result == nil {
return nil, fmt.Errorf("No hook found for event type %s", eventType)
}
return result, nil
}
func (m *MangoPay) Hooks() (HookList, error) {
list, err := m.anyRequest(new(HookList), actionFetchAllHooks, nil)
if err != nil {
return nil, err
}
casted := *(list.(*HookList))
for _, hook := range casted {
hook.service = m
}
return casted, nil
}
type HookList []*Hook