-
Notifications
You must be signed in to change notification settings - Fork 2
/
graphql_public.go
89 lines (67 loc) · 1.95 KB
/
graphql_public.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
package api_public
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/pdcgo/common_conf/pdc_common"
)
type GraphqlPayload struct {
OperationName string `json:"operationName"`
Variables interface{} `json:"variables"`
Query string `json:"query"`
}
func (api *TokopediaApiPublic) graphqlDefaultHeader(req *http.Request) {
headers := map[string]string{
"User-Agent": api.Session.Ua,
"Content-Type": "application/json",
"Origin": "https://www.tokopedia.com",
}
for key, value := range headers {
req.Header.Set(key, value)
}
}
func (api *TokopediaApiPublic) NewGraphqlReq(payload *GraphqlPayload) *http.Request {
ur := fmt.Sprintf("https://gql.tokopedia.com/graphql/%s", payload.OperationName)
dataraw, err := json.Marshal(payload)
if err != nil {
pdc_common.ReportError(err)
}
req, err := http.NewRequest(http.MethodPost, ur, bytes.NewReader(dataraw))
if err != nil {
pdc_common.ReportError(err)
}
api.graphqlDefaultHeader(req)
for _, cookie := range api.Session.Cookies {
req.AddCookie(cookie)
}
return req
}
var ErrGraphqlBatchNoOperationName = errors.New("graphql batch no operation name")
var ErrGraphqlBatchNoQuery = errors.New("graphql batch no query")
func (api *TokopediaApiPublic) NewGraphqlReqBatch(operationName string, payloads []*GraphqlPayload) (*http.Request, error) {
if operationName == "" {
return nil, ErrGraphqlBatchNoOperationName
}
if len(payloads) == 0 {
return nil, ErrGraphqlBatchNoQuery
}
for _, payload := range payloads {
payload.OperationName = operationName
}
ur := fmt.Sprintf("https://gql.tokopedia.com/graphql/%s", operationName)
dataraw, err := json.Marshal(payloads)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, ur, bytes.NewReader(dataraw))
if err != nil {
return req, err
}
api.graphqlDefaultHeader(req)
for _, cookie := range api.Session.Cookies {
req.AddCookie(cookie)
}
return req, nil
}