Test Setup Failed
Push — main ( ca941c...e4ed3b )
by Acho
02:26
created

mtnmomo.*Client.addTargetEnvironment   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
package mtnmomo
2
3
import (
4
	"bytes"
5
	"context"
6
	"encoding/json"
7
	"io"
8
	"io/ioutil"
9
	"net/http"
10
	"sync"
11
)
12
13
const (
14
	headerKeySubscriptionKey   = "Ocp-Apim-Subscription-Key"
15
	headerKeyTargetEnvironment = "X-Target-Environment"
16
	headerKeyReferenceID       = "X-Reference-Id"
17
	headerKeyCallbackURL       = "X-Callback-Url"
18
)
19
20
type service struct {
21
	client *Client
22
}
23
24
// Client is the campay API client.
25
// Do not instantiate this client with Client{}. Use the New method instead.
26
type Client struct {
27
	httpClient        *http.Client
28
	common            service
29
	baseURL           string
30
	subscriptionKey   string
31
	apiUser           string
32
	apiKey            string
33
	targetEnvironment string
34
35
	collectionLock                 sync.Mutex
36
	collectionAccessToken          string
37
	collectionAccessTokenExpiresAt int64
38
39
	APIUser    *apiUserService
40
	Collection *collectionService
41
}
42
43
// New creates and returns a new campay.Client from a slice of campay.ClientOption.
44
func New(options ...Option) *Client {
45
	config := defaultClientConfig()
46
47
	for _, option := range options {
48
		option.apply(config)
49
	}
50
51
	client := &Client{
52
		httpClient:        config.httpClient,
53
		subscriptionKey:   config.subscriptionKey,
54
		baseURL:           config.baseURL,
55
		apiKey:            config.apiKey,
56
		apiUser:           config.apiUser,
57
		targetEnvironment: config.targetEnvironment,
58
		collectionLock:    sync.Mutex{},
59
	}
60
61
	client.common.client = client
62
	client.APIUser = (*apiUserService)(&client.common)
63
	client.Collection = (*collectionService)(&client.common)
64
	return client
65
}
66
67
// newRequest creates an API request. A relative URL can be provided in uri,
68
// in which case it is resolved relative to the BaseURL of the Client.
69
// URI's should always be specified without a preceding slash.
70
func (client *Client) newRequest(ctx context.Context, method, uri string, body interface{}) (*http.Request, error) {
71
	var buf io.ReadWriter
72
	if body != nil {
73
		buf = &bytes.Buffer{}
74
		enc := json.NewEncoder(buf)
75
		enc.SetEscapeHTML(false)
76
		err := enc.Encode(body)
77
		if err != nil {
78
			return nil, err
79
		}
80
	}
81
82
	req, err := http.NewRequestWithContext(ctx, method, client.baseURL+uri, buf)
83
	if err != nil {
84
		return nil, err
85
	}
86
87
	req.Header.Set("Content-Type", "application/json")
88
	req.Header.Set("Accept", "application/json")
89
	req.Header.Set(headerKeySubscriptionKey, client.subscriptionKey)
90
91
	return req, nil
92
}
93
94
/*
95
// addURLParams adds urls parameters to an *http.Request
96
func (client *Client) addURLParams(request *http.Request, params map[string]string) *http.Request {
97
	q := request.URL.Query()
98
	for key, value := range params {
99
		q.Add(key, value)
100
	}
101
	request.URL.RawQuery = q.Encode()
102
	return request
103
}
104
*/
105
106
func (client *Client) addCollectionAccessToken(request *http.Request) {
107
	request.Header.Add("Authorization", "Bearer "+client.collectionAccessToken)
108
}
109
110
func (client *Client) addBasicAuth(request *http.Request) {
111
	request.SetBasicAuth(client.apiUser, client.apiKey)
112
}
113
114
func (client *Client) addReferenceID(request *http.Request, reference string) {
115
	request.Header.Set(headerKeyReferenceID, reference)
116
}
117
118
func (client *Client) addCallbackURL(request *http.Request, url string) {
119
	request.Header.Set(headerKeyCallbackURL, url)
120
}
121
122
func (client *Client) addTargetEnvironment(request *http.Request) {
123
	request.Header.Set(headerKeyTargetEnvironment, client.targetEnvironment)
124
}
125
126
// do carries out an HTTP request and returns a Response
127
func (client *Client) do(req *http.Request) (*Response, error) {
128
	httpResponse, err := client.httpClient.Do(req)
129
	if err != nil {
130
		return nil, err
131
	}
132
133
	defer func() { _ = httpResponse.Body.Close() }()
134
135
	resp, err := client.newResponse(httpResponse)
136
	if err != nil {
137
		return resp, err
138
	}
139
140
	_, err = io.Copy(ioutil.Discard, httpResponse.Body)
141
	if err != nil {
142
		return resp, err
143
	}
144
145
	return resp, nil
146
}
147
148
// newResponse converts an *http.Response to *Response
149
func (client *Client) newResponse(httpResponse *http.Response) (*Response, error) {
150
	response := new(Response)
151
	response.HTTPResponse = httpResponse
152
153
	buf, err := ioutil.ReadAll(response.HTTPResponse.Body)
154
	if err != nil {
155
		return nil, err
156
	}
157
	response.Body = &buf
158
159
	return response, response.Error()
160
}
161