/
invdmockrraction.go
125 lines (89 loc) · 2.39 KB
/
invdmockrraction.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 invdmockserver
import (
"github.com/Invoiced/invoiced-go/v2/invdutil"
)
type RequestObject struct {
Method string `json:"method,omitempty"`
Url string `json:"url,omitempty"`
Body []BodyPatterns `json:"bodyPatterns"`
}
type ResponseObject struct {
Status int `json:"status,omitempty"`
Body string `json:"body,omitempty"`
}
type RRActionObject struct {
Request RequestObject `json:"request,omitempty"`
Response ResponseObject `json:"response,omitempty"`
}
type BodyPatterns struct {
EqualToJson string `json:"equalToJson,omitempty"`
}
type RRActionMap struct {
store map[string]map[string][]*RRActionObject
}
func NewRRActionMap() *RRActionMap {
store := make(map[string]map[string][]*RRActionObject)
rrActionMap := new(RRActionMap)
rrActionMap.store = store
return rrActionMap
}
func (r *RRActionMap) Put(rrActionObject *RRActionObject) error {
method := rrActionObject.Request.Method
url := rrActionObject.Request.Url
_, found0 := r.store[url]
if !found0 {
r.store[url] = make(map[string][]*RRActionObject)
}
rrActionObjects, found := r.store[url][method]
if !found {
r.store[url][method] = append(r.store[url][method], rrActionObject)
} else {
for _, rrActionObjectItem := range rrActionObjects {
jsonBody1 := "{}"
jsonBody2 := "{}"
if len(rrActionObjectItem.Request.Body) > 0 {
jsonBody1 = rrActionObjectItem.Request.Body[0].EqualToJson
}
if len(rrActionObject.Request.Body) > 0 {
jsonBody2 = rrActionObject.Request.Body[0].EqualToJson
}
equal, err := invdutil.JsonEqual(jsonBody1, jsonBody2)
if err != nil {
return err
}
if equal {
return nil
}
}
r.store[url][method] = append(r.store[url][method], rrActionObject)
}
return nil
}
func (r *RRActionMap) Get(method, url, body string) (*RRActionObject, bool, error) {
if len(body) == 0 {
body = "{}"
}
_, found0 := r.store[url]
if !found0 {
return nil, false, nil
}
rrActionObjects, found := r.store[url][method]
if !found {
return nil, false, nil
}
for _, rrActionObject := range rrActionObjects {
jsonBody1 := "{}"
if len(rrActionObject.Request.Body) > 0 {
jsonBody1 = rrActionObject.Request.Body[0].EqualToJson
}
jsonBody2 := body
equal, err := invdutil.JsonEqual(jsonBody1, jsonBody2)
if err != nil {
return nil, false, err
}
if equal {
return rrActionObject, true, nil
}
}
return nil, false, nil
}