-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
102 lines (87 loc) · 1.84 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package sn
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
)
type Client struct {
BaseUrl string
ApiUrl string
ApiKey string
MediaUrl string
}
func NewClient(options ...func(*Client)) *Client {
c := &Client{}
for _, o := range options {
o(c)
}
// set defaults
if c.BaseUrl == "" {
c.BaseUrl = "https://stacker.news"
}
if c.ApiKey == "" {
c.ApiKey = os.Getenv("SN_API_KEY")
}
if c.MediaUrl == "" {
c.MediaUrl = "https://m.stacker.news"
}
c.ApiUrl = fmt.Sprintf("%s/api/graphql", c.BaseUrl)
return c
}
func WithApiKey(apiKey string) func(*Client) {
return func(c *Client) {
c.ApiKey = apiKey
}
}
func WithBaseUrl(baseUrl string) func(*Client) {
return func(c *Client) {
c.BaseUrl = baseUrl
}
}
func WithMediaUrl(mediaUrl string) func(*Client) {
return func(c *Client) {
c.MediaUrl = mediaUrl
}
}
type GqlBody struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
type GqlError struct {
Message string `json:"message"`
}
func (c *Client) callApi(body GqlBody) (*http.Response, error) {
bodyJSON, err := json.Marshal(body)
if err != nil {
err = fmt.Errorf("error encoding SN payload: %w", err)
return nil, err
}
req, err := http.NewRequest("POST", c.ApiUrl, bytes.NewBuffer(bodyJSON))
if err != nil {
err = fmt.Errorf("error preparing SN request: %w", err)
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if c.ApiKey != "" {
req.Header.Set("X-Api-Key", c.ApiKey)
}
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *Client) checkForErrors(err []GqlError) error {
if len(err) > 0 {
errMsg, marshalErr := json.Marshal(err)
if marshalErr != nil {
return marshalErr
}
return errors.New(string(errMsg))
}
return nil
}