/
compound.go
111 lines (88 loc) · 2.36 KB
/
compound.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
package client
import (
"github.com/secr3t/otcommerce-client/model"
"log"
"sync"
"time"
)
const defaultLimit = 200
type CompoundClient struct {
ApiKey string
SearchLimit int
}
func NewCompoundClient(apiKey string, searchLimit int) *CompoundClient {
if searchLimit > defaultLimit {
searchLimit = defaultLimit
}
return &CompoundClient{
ApiKey: apiKey,
SearchLimit: searchLimit,
}
}
func (c *CompoundClient) SearchAndGetDetail(param *SearchParam) ([]model.DetailItem, error) {
limit := c.SearchLimit
sc := NewSearchClient(c.ApiKey)
dc := NewDetailClient(c.ApiKey)
detailItems := make([]model.DetailItem, 0)
result, err := sc.SearchItems(*param)
if err != nil {
return nil, err
}
if limit > result.TotalCount {
limit = result.TotalCount
}
limit -= len(result.Items)
for _, item := range result.Items {
detailItem, err := dc.GetDetail(item)
if err != nil {
log.Printf("id %s fetch failed", detailItem.NumIid)
} else {
detailItems = append(detailItems, *detailItem)
}
}
param.Page += result.FrameSize
for ;limit > 0; limit -= len(result.Items) {
result, err = sc.SearchItems(*param)
for _, item := range result.Items {
detailItem, err := dc.GetDetail(item)
if err != nil {
log.Printf("id %s fetch failed", detailItem.NumIid)
} else {
detailItems = append(detailItems, *detailItem)
}
}
param.Page += result.FrameSize
}
return detailItems, nil
}
func (c *CompoundClient) SearchAndGetDetailsMultiRequestOneTime(param *SearchParam) (chan model.DetailItem, error) {
items := NewSearchClient(c.ApiKey).SearchTilLimit(param, c.SearchLimit)
return c.GetDetails(items)
}
func (c *CompoundClient) GetDetails(items []model.Item) (chan model.DetailItem, error) {
var wg sync.WaitGroup
itemLen := len(items)
wg.Add(itemLen)
detailChan := make(chan model.DetailItem, itemLen)
for i, item := range items {
go c.backgroundDetailRequestItem(&wg, item, detailChan, int64(i))
}
defer func() {
go func() {
wg.Wait()
close(detailChan)
}()
}()
return detailChan, nil
}
func (c *CompoundClient) backgroundDetailRequestItem(wg *sync.WaitGroup, item model.Item, ch chan model.DetailItem, sleepDelta int64) {
time.Sleep(time.Millisecond * time.Duration(sleepDelta * 50))
dc := NewDetailClient(c.ApiKey)
detail, err := dc.GetDetail(item)
if err == nil {
ch <- *detail
} else {
log.Println(err)
}
wg.Done()
}