-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
88 lines (72 loc) · 2.04 KB
/
client.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
package nrdb
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
type Client interface {
WithHTTPClient(http.Client) Client
CardCycles() ([]*CardCycle, error)
CardPools() ([]*CardPool, error)
CardSetTypes() ([]*CardSetType, error)
CardSets(*CardSetFilter) ([]*CardSet, error)
CardSubtypes() ([]*CardSubtype, error)
CardTypes(*CardTypeFilter) ([]*CardType, error)
Cards(*CardFilter) ([]*Card, error)
AllCards(*CardFilter) ([]*Card, error)
Card(cardID string) (*Card, error)
Factions(*FactionFilter) ([]*Faction, error)
Faction(factionID string) (*Faction, error)
Formats() ([]*Format, error)
Format(formatID string) (*Format, error)
Illustrators() ([]*Illustrator, error)
Illustrator(illustratorID string) (*Illustrator, error)
Printings(*PrintingFilter) ([]*Printing, error)
AllPrintings(*PrintingFilter) ([]*Printing, error)
Printing(printingID string) (*Printing, error)
}
type Filter interface {
Query() (url.Values, error)
}
type client struct {
http http.Client
}
var defaultHTTPClient = http.Client{Timeout: time.Second * 30}
func NewClient() Client {
return client{
http: defaultHTTPClient,
}
}
func (cl client) WithHTTPClient(httpClient http.Client) Client {
cl.http = httpClient
return cl
}
func (cl client) nrdbReq(path string, out any, query url.Values) error {
reqURL := url.URL{
Scheme: "https",
Host: "api-preview.netrunnerdb.com",
Path: fmt.Sprintf("/api/v3/public/%s", path),
RawQuery: query.Encode(),
}
// log.Println(reqURL.String())
return cl.doNRDBReq(reqURL.String(), out)
}
func (cl client) doNRDBReq(reqURL string, out any) error {
req, err := http.NewRequest(http.MethodGet, reqURL, nil)
if err != nil {
return fmt.Errorf("making request: %w", err)
}
res, err := cl.http.Do(req)
if err != nil {
return fmt.Errorf("making request: %w", err)
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected %d status", res.StatusCode)
}
if err := json.NewDecoder(res.Body).Decode(out); err != nil {
return fmt.Errorf("parsing payload: %w", err)
}
return nil
}