Skip to content

Commit 89c78ea

Browse files
authored
Merge pull request #36 from romanyx/refactor/client_v2
V5 client version
2 parents 2eed9fe + 25d4f23 commit 89c78ea

14 files changed

+28
-250
lines changed

README.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,14 @@ Now you can query the API for information or send data. For example, if we want
3838
// Request the balance information, returned as a Balance object.
3939
balance, err := client.Balance()
4040
if err != nil {
41-
// messagebird.ErrResponse means custom JSON errors.
42-
if err == messagebird.ErrResponse {
43-
for _, mbError := range balance.Errors {
44-
fmt.Printf("Error: %#v\n", mbError)
45-
}
46-
}
47-
48-
return
41+
switch errResp := err.(type) {
42+
case messagebird.ErrorResponse:
43+
for _, mbError := range errResp.Errors {
44+
fmt.Printf("Error: %#v\n", mbError)
45+
}
46+
}
47+
48+
return
4949
}
5050

5151
fmt.Println(" payment :", balance.Payment)

balance.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,4 @@ type Balance struct {
55
Payment string
66
Type string
77
Amount float32
8-
Errors []Error // Deprecated: errors now returned at ErrorResponse instance as error.
98
}

client.go

Lines changed: 1 addition & 169 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,6 @@ const (
5050
)
5151

5252
var (
53-
// ErrResponse is returned when we were able to contact API but request was not successful and contains error details.
54-
ErrResponse = errors.New("The MessageBird API returned an error")
55-
5653
// ErrUnexpectedResponse is used when there was an internal server error and nothing can be done at this point.
5754
ErrUnexpectedResponse = errors.New("The MessageBird API is currently unavailable")
5855
)
@@ -63,118 +60,20 @@ type Client struct {
6360
AccessKey string // The API access key
6461
HTTPClient *http.Client // The HTTP client to send requests on
6562
DebugLog *log.Logger // Optional logger for debugging purposes
66-
request func(c *Client, v interface{}, method, path string, data interface{}) error
67-
}
68-
69-
// NewV2 creates a new MessageBird client object.
70-
// If the request to MessageBird API will return an
71-
// error, it will be returned as ErrorResponse instance
72-
// typed as the error, containing all codes,
73-
// descriptions and properies.
74-
func NewV2(accessKey string) *Client {
75-
return &Client{
76-
AccessKey: accessKey,
77-
HTTPClient: &http.Client{
78-
Timeout: httpClientTimeout,
79-
},
80-
request: requestV2,
81-
}
8263
}
8364

8465
// New creates a new MessageBird client object.
85-
// If the request to MessageBird API will return
86-
// and error, it will simply return ErrResponse.
87-
// Deprecated: use NewV2 until v2 release.
8866
func New(accessKey string) *Client {
8967
return &Client{
9068
AccessKey: accessKey,
9169
HTTPClient: &http.Client{
9270
Timeout: httpClientTimeout,
9371
},
94-
request: requestV1,
9572
}
9673
}
9774

9875
// Request is for internal use only and unstable.
9976
func (c *Client) Request(v interface{}, method, path string, data interface{}) error {
100-
return c.request(c, v, method, path, data)
101-
}
102-
103-
func requestV1(c *Client, v interface{}, method, path string, data interface{}) error {
104-
if !strings.HasPrefix(path, "https://") && !strings.HasPrefix(path, "http://") {
105-
path = fmt.Sprintf("%s/%s", Endpoint, path)
106-
}
107-
uri, err := url.Parse(path)
108-
if err != nil {
109-
return err
110-
}
111-
112-
var jsonEncoded []byte
113-
if data != nil {
114-
jsonEncoded, err = json.Marshal(data)
115-
if err != nil {
116-
return err
117-
}
118-
}
119-
120-
request, err := http.NewRequest(method, uri.String(), bytes.NewBuffer(jsonEncoded))
121-
if err != nil {
122-
return err
123-
}
124-
125-
request.Header.Set("Content-Type", "application/json")
126-
request.Header.Set("Accept", "application/json")
127-
request.Header.Set("Authorization", "AccessKey "+c.AccessKey)
128-
request.Header.Set("User-Agent", "MessageBird/ApiClient/"+ClientVersion+" Go/"+runtime.Version())
129-
130-
if c.DebugLog != nil {
131-
if data != nil {
132-
c.DebugLog.Printf("HTTP REQUEST: %s %s %s", method, uri.String(), jsonEncoded)
133-
} else {
134-
c.DebugLog.Printf("HTTP REQUEST: %s %s", method, uri.String())
135-
}
136-
}
137-
138-
response, err := c.HTTPClient.Do(request)
139-
if err != nil {
140-
return err
141-
}
142-
143-
defer response.Body.Close()
144-
145-
responseBody, err := ioutil.ReadAll(response.Body)
146-
if err != nil {
147-
return err
148-
}
149-
150-
if c.DebugLog != nil {
151-
c.DebugLog.Printf("HTTP RESPONSE: %s", string(responseBody))
152-
}
153-
154-
// Status code 500 is a server error and means nothing can be done at this
155-
// point.
156-
if response.StatusCode == 500 {
157-
return ErrUnexpectedResponse
158-
}
159-
// Status codes 200 and 201 are indicative of being able to convert the
160-
// response body to the struct that was specified.
161-
if response.StatusCode == 200 || response.StatusCode == 201 {
162-
if err := json.Unmarshal(responseBody, &v); err != nil {
163-
return fmt.Errorf("could not decode response JSON, %s: %v", string(responseBody), err)
164-
}
165-
return nil
166-
}
167-
168-
// We're dealing with an API error here. try to decode it, but don't do
169-
// anything with the error. This is because not all values of `v` have
170-
// `Error` properties and decoding could fail.
171-
json.Unmarshal(responseBody, &v)
172-
173-
// Anything else than a 200/201/500 should be a JSON error.
174-
return ErrResponse
175-
}
176-
177-
func requestV2(c *Client, v interface{}, method, path string, data interface{}) error {
17877
if !strings.HasPrefix(path, "https://") && !strings.HasPrefix(path, "http://") {
17978
path = fmt.Sprintf("%s/%s", Endpoint, path)
18079
}
@@ -253,10 +152,6 @@ func requestV2(c *Client, v interface{}, method, path string, data interface{})
253152
func (c *Client) Balance() (*Balance, error) {
254153
balance := &Balance{}
255154
if err := c.Request(balance, http.MethodGet, "balance", nil); err != nil {
256-
if err == ErrResponse {
257-
return balance, err
258-
}
259-
260155
return nil, err
261156
}
262157

@@ -268,10 +163,6 @@ func (c *Client) Balance() (*Balance, error) {
268163
func (c *Client) HLR(id string) (*HLR, error) {
269164
hlr := &HLR{}
270165
if err := c.Request(hlr, http.MethodGet, HLRPath+"/"+id, nil); err != nil {
271-
if err == ErrResponse {
272-
return hlr, err
273-
}
274-
275166
return nil, err
276167
}
277168

@@ -283,10 +174,6 @@ func (c *Client) HLR(id string) (*HLR, error) {
283174
func (c *Client) HLRs() (*HLRList, error) {
284175
hlrList := &HLRList{}
285176
if err := c.Request(hlrList, http.MethodGet, HLRPath, nil); err != nil {
286-
if err == ErrResponse {
287-
return hlrList, err
288-
}
289-
290177
return nil, err
291178
}
292179

@@ -303,10 +190,6 @@ func (c *Client) NewHLR(msisdn string, reference string) (*HLR, error) {
303190
hlr := &HLR{}
304191

305192
if err := c.Request(hlr, http.MethodPost, HLRPath, requestData); err != nil {
306-
if err == ErrResponse {
307-
return hlr, err
308-
}
309-
310193
return nil, err
311194
}
312195

@@ -317,10 +200,6 @@ func (c *Client) NewHLR(msisdn string, reference string) (*HLR, error) {
317200
func (c *Client) Message(id string) (*Message, error) {
318201
message := &Message{}
319202
if err := c.Request(message, http.MethodGet, MessagePath+"/"+id, nil); err != nil {
320-
if err == ErrResponse {
321-
return message, err
322-
}
323-
324203
return nil, err
325204
}
326205

@@ -336,10 +215,6 @@ func (c *Client) Messages(msgListParams *MessageListParams) (*MessageList, error
336215
}
337216

338217
if err := c.Request(messageList, http.MethodGet, MessagePath+"?"+params.Encode(), nil); err != nil {
339-
if err == ErrResponse {
340-
return messageList, err
341-
}
342-
343218
return nil, err
344219
}
345220

@@ -355,10 +230,6 @@ func (c *Client) NewMessage(originator string, recipients []string, body string,
355230

356231
message := &Message{}
357232
if err := c.Request(message, http.MethodPost, MessagePath, requestData); err != nil {
358-
if err == ErrResponse {
359-
return message, err
360-
}
361-
362233
return nil, err
363234
}
364235

@@ -369,10 +240,6 @@ func (c *Client) NewMessage(originator string, recipients []string, body string,
369240
func (c *Client) MMSMessage(id string) (*MMSMessage, error) {
370241
mmsMessage := &MMSMessage{}
371242
if err := c.Request(mmsMessage, http.MethodGet, MMSPath+"/"+id, nil); err != nil {
372-
if err == ErrResponse {
373-
return mmsMessage, err
374-
}
375-
376243
return nil, err
377244
}
378245

@@ -391,10 +258,6 @@ func (c *Client) NewMMSMessage(originator string, recipients []string, msgParams
391258

392259
mmsMessage := &MMSMessage{}
393260
if err := c.Request(mmsMessage, http.MethodPost, MMSPath, params); err != nil {
394-
if err == ErrResponse {
395-
return mmsMessage, err
396-
}
397-
398261
return nil, err
399262
}
400263

@@ -405,10 +268,6 @@ func (c *Client) NewMMSMessage(originator string, recipients []string, msgParams
405268
func (c *Client) VoiceMessage(id string) (*VoiceMessage, error) {
406269
message := &VoiceMessage{}
407270
if err := c.Request(message, http.MethodGet, VoiceMessagePath+"/"+id, nil); err != nil {
408-
if err == ErrResponse {
409-
return message, err
410-
}
411-
412271
return nil, err
413272
}
414273

@@ -419,10 +278,6 @@ func (c *Client) VoiceMessage(id string) (*VoiceMessage, error) {
419278
func (c *Client) VoiceMessages() (*VoiceMessageList, error) {
420279
messageList := &VoiceMessageList{}
421280
if err := c.Request(messageList, http.MethodGet, VoiceMessagePath, nil); err != nil {
422-
if err == ErrResponse {
423-
return messageList, err
424-
}
425-
426281
return nil, err
427282
}
428283

@@ -438,10 +293,6 @@ func (c *Client) NewVoiceMessage(recipients []string, body string, params *Voice
438293

439294
message := &VoiceMessage{}
440295
if err := c.Request(message, http.MethodPost, VoiceMessagePath, requestData); err != nil {
441-
if err == ErrResponse {
442-
return message, err
443-
}
444-
445296
return nil, err
446297
}
447298

@@ -457,10 +308,6 @@ func (c *Client) NewVerify(recipient string, params *VerifyParams) (*Verify, err
457308

458309
verify := &Verify{}
459310
if err := c.Request(verify, http.MethodPost, VerifyPath, requestData); err != nil {
460-
if err == ErrResponse {
461-
return verify, err
462-
}
463-
464311
return nil, err
465312
}
466313

@@ -476,10 +323,6 @@ func (c *Client) VerifyToken(id, token string) (*Verify, error) {
476323

477324
verify := &Verify{}
478325
if err := c.Request(verify, http.MethodGet, path, nil); err != nil {
479-
if err == ErrResponse {
480-
return verify, err
481-
}
482-
483326
return nil, err
484327
}
485328

@@ -492,10 +335,7 @@ func (c *Client) Lookup(phoneNumber string, params *LookupParams) (*Lookup, erro
492335
path := LookupPath + "/" + phoneNumber + "?" + urlParams.Encode()
493336

494337
lookup := &Lookup{}
495-
if err := c.Request(lookup, http.MethodGet, path, nil); err != nil {
496-
if err == ErrResponse {
497-
return lookup, err
498-
}
338+
if err := c.Request(lookup, http.MethodPost, path, nil); err != nil {
499339
return nil, err
500340
}
501341

@@ -509,10 +349,6 @@ func (c *Client) NewLookupHLR(phoneNumber string, params *LookupParams) (*HLR, e
509349

510350
hlr := &HLR{}
511351
if err := c.Request(hlr, http.MethodPost, path, requestData); err != nil {
512-
if err == ErrResponse {
513-
return hlr, err
514-
}
515-
516352
return nil, err
517353
}
518354

@@ -526,10 +362,6 @@ func (c *Client) LookupHLR(phoneNumber string, params *LookupParams) (*HLR, erro
526362

527363
hlr := &HLR{}
528364
if err := c.Request(hlr, http.MethodGet, path, nil); err != nil {
529-
if err == ErrResponse {
530-
return hlr, err
531-
}
532-
533365
return nil, err
534366
}
535367

error.go

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package messagebird
22

3-
import "fmt"
3+
const (
4+
apiErrMessage = "The MessageBird API returned an error"
5+
)
46

57
// Error holds details including error code, human readable description and optional parameter that is related to the error.
68
type Error struct {
@@ -9,20 +11,17 @@ type Error struct {
911
Parameter string
1012
}
1113

14+
// Error implements error interface.
15+
func (e Error) Error() string {
16+
return e.Description
17+
}
18+
1219
// ErrorResponse represents errored API response.
1320
type ErrorResponse struct {
1421
Errors []Error `json:"errors"`
1522
}
1623

1724
// Error implements error interface.
1825
func (r ErrorResponse) Error() string {
19-
eString := "API returned an error: "
20-
for i, e := range r.Errors {
21-
eString = eString + fmt.Sprintf("code: %d, description: %s, parameter: %s", e.Code, e.Description, e.Parameter)
22-
if i < len(r.Errors)-1 {
23-
eString = eString + ", "
24-
}
25-
}
26-
27-
return eString
26+
return apiErrMessage
2827
}

0 commit comments

Comments
 (0)