Test Setup Failed
Push — main ( 273289...2d1dd5 )
by Acho
02:18
created

mtnmomo.*Client.addAccessToken   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
	apiKey            string
32
	apiUser           string
33
	targetEnvironment string
34
35
	accessTokenLock      sync.Mutex
36
	accessToken          string
37
	accessTokenExpiresAt int64
38
39
	APIUser      *apiUserService
40
	Collection   *collectionService
41
	Disbursement *disbursementsService
42
}
43
44
// New creates and returns a new campay.Client from a slice of campay.ClientOption.
45
func New(options ...Option) *Client {
46
	config := defaultClientConfig()
47
48
	for _, option := range options {
49
		option.apply(config)
50
	}
51
52
	client := &Client{
53
		httpClient:        config.httpClient,
54
		subscriptionKey:   config.subscriptionKey,
55
		baseURL:           config.baseURL,
56
		apiKey:            config.apiKey,
57
		apiUser:           config.apiUser,
58
		targetEnvironment: config.targetEnvironment,
59
	}
60
61
	client.common.client = client
62
	client.APIUser = (*apiUserService)(&client.common)
63
	client.Collection = (*collectionService)(&client.common)
64
	client.Disbursement = (*disbursementsService)(&client.common)
65
66
	return client
67
}
68
69
// newRequest creates an API request. A relative URL can be provided in uri,
70
// in which case it is resolved relative to the BaseURL of the Client.
71
// URI's should always be specified without a preceding slash.
72
func (client *Client) newRequest(ctx context.Context, method, uri string, body interface{}) (*http.Request, error) {
73
	var buf io.ReadWriter
74
	if body != nil {
75
		buf = &bytes.Buffer{}
76
		enc := json.NewEncoder(buf)
77
		enc.SetEscapeHTML(false)
78
		err := enc.Encode(body)
79
		if err != nil {
80
			return nil, err
81
		}
82
	}
83
84
	req, err := http.NewRequestWithContext(ctx, method, client.baseURL+uri, buf)
85
	if err != nil {
86
		return nil, err
87
	}
88
89
	req.Header.Set("Content-Type", "application/json")
90
	req.Header.Set("Accept", "application/json")
91
	req.Header.Set(headerKeySubscriptionKey, client.subscriptionKey)
92
93
	return req, nil
94
}
95
96
func (client *Client) addAccessToken(request *http.Request) {
97
	request.Header.Add("Authorization", "Bearer "+client.accessToken)
98
}
99
100
func (client *Client) addBasicAuth(request *http.Request) {
101
	request.SetBasicAuth(client.apiUser, client.apiKey)
102
}
103
104
func (client *Client) addReferenceID(request *http.Request, reference string) {
105
	request.Header.Set(headerKeyReferenceID, reference)
106
}
107
108
func (client *Client) addCallbackURL(request *http.Request, url string) {
109
	request.Header.Set(headerKeyCallbackURL, url)
110
}
111
112
func (client *Client) addTargetEnvironment(request *http.Request) {
113
	request.Header.Set(headerKeyTargetEnvironment, client.targetEnvironment)
114
}
115
116
// do carries out an HTTP request and returns a Response
117
func (client *Client) do(req *http.Request) (*Response, error) {
118
	httpResponse, err := client.httpClient.Do(req)
119
	if err != nil {
120
		return nil, err
121
	}
122
123
	defer func() { _ = httpResponse.Body.Close() }()
124
125
	resp, err := client.newResponse(httpResponse)
126
	if err != nil {
127
		return resp, err
128
	}
129
130
	_, err = io.Copy(ioutil.Discard, httpResponse.Body)
131
	if err != nil {
132
		return resp, err
133
	}
134
135
	return resp, nil
136
}
137
138
// newResponse converts an *http.Response to *Response
139
func (client *Client) newResponse(httpResponse *http.Response) (*Response, error) {
140
	response := new(Response)
141
	response.HTTPResponse = httpResponse
142
143
	buf, err := ioutil.ReadAll(response.HTTPResponse.Body)
144
	if err != nil {
145
		return nil, err
146
	}
147
	response.Body = &buf
148
149
	return response, response.Error()
150
}
151