-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethods.go
More file actions
112 lines (101 loc) · 2.24 KB
/
methods.go
File metadata and controls
112 lines (101 loc) · 2.24 KB
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
package belt
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"github.com/mitchellh/mapstructure"
)
func (f *Factory) Map(mapper Mapper) *Factory {
if f.options.sync {
return f.SyncMap(mapper)
}
for idx, item := range f.items {
newItem, err := mapper(item, idx)
errorHandlerWithFatal(err)
f.items[idx] = newItem
}
return f
}
func (f *Factory) Filter(filter Filter) *Factory {
if f.options.sync {
return f.SyncFilter(filter)
}
items := make([]I, 0)
for idx, item := range f.items {
ok, err := filter(item, idx)
errorHandlerWithFatal(err)
if ok {
items = append(items, item)
}
}
f.items = items
return f
}
func (f *Factory) Pipe(piper Piper) *Factory {
if err := piper(f.items); err != nil {
panic(err)
}
return f
}
func (f *Factory) Append(items ...I) *Factory {
f.items = append(f.items, items...)
return f
}
func (f *Factory) Build() []I {
return f.items
}
func (f *Factory) SyncMap(mapper Mapper) *Factory {
var wg sync.WaitGroup
wg.Add(len(f.items))
for idx, item := range f.items {
go func(idx int, item I) {
defer wg.Done()
newItem, err := mapper(item, idx)
errorHandlerWithPanic(err)
f.items[idx] = newItem
}(idx, item)
}
wg.Wait()
return f
}
func (f *Factory) SyncFilter(filter Filter) *Factory {
items := make([]I, 0)
var wg sync.WaitGroup
var mutex = new(sync.Mutex)
wg.Add(len(f.items))
for idx, item := range f.items {
go func(idx int, item I) {
defer wg.Done()
defer mutex.Unlock()
ok, err := filter(item, idx)
errorHandlerWithPanic(err)
mutex.Lock()
if ok {
items = append(items, item)
}
}(idx, item)
}
wg.Wait()
f.items = items
return f
}
func (f *Factory) FromQuery(dbSource string, output interface{}, query string, args ...interface{}) *Factory {
f.items = getFromMySql(dbSource, output, query, args...)
return f
}
func (f *Factory) FromHttp(url string, output interface{}) *Factory {
res, err := http.Get(url)
errorHandlerWithFatal(err)
checkStatusCode(res)
defer res.Body.Close()
outputs, results := []I{}, []I{}
json.NewDecoder(res.Body).Decode(&outputs)
for _, item := range outputs {
mapstructure.Decode(item.(map[string]interface{}), &output)
results = append(results, output)
fmt.Println(item, output)
}
f.items = results
return f
}