-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_unitgroup_list.go
More file actions
98 lines (82 loc) · 2.25 KB
/
client_unitgroup_list.go
File metadata and controls
98 lines (82 loc) · 2.25 KB
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
package mapon
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
maponv1 "github.com/way-platform/mapon-go/proto/gen/go/wayplatform/connect/mapon/v1"
)
// This API endpoint is documented in:
// docs/api/methods/10-method-unit_groups.html
// ListUnitGroups lists unit groups.
func (c *Client) ListUnitGroups(
ctx context.Context,
request *maponv1.ListUnitGroupsRequest,
) (_ *maponv1.ListUnitGroupsResponse, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("mapon: list unit groups: %w", err)
}
}()
params := url.Values{}
if request.GetUnitId() != 0 {
params.Add("unit_id", strconv.FormatInt(request.GetUnitId(), 10))
}
requestURL, err := url.Parse(c.baseURL + "/unit_groups/list.json")
if err != nil {
return nil, fmt.Errorf("invalid request URL: %w", err)
}
requestURL.RawQuery = params.Encode()
httpRequest, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL.String(), nil)
if err != nil {
return nil, err
}
httpRequest.Header.Set("User-Agent", getUserAgent())
httpResponse, err := c.httpClient(c.config).Do(httpRequest)
if err != nil {
return nil, err
}
defer func() { _ = httpResponse.Body.Close() }()
if httpResponse.StatusCode != http.StatusOK {
return nil, newResponseError(httpResponse)
}
data, err := io.ReadAll(httpResponse.Body)
if err != nil {
return nil, err
}
var responseBody jsonUnitGroupsResponse
if err := json.Unmarshal(data, &responseBody); err != nil {
return nil, err
}
if responseBody.Error != nil {
return nil, fmt.Errorf("api error %d: %s", responseBody.Error.Code, responseBody.Error.Msg)
}
var groups []*maponv1.UnitGroup
for _, g := range responseBody.Data {
grp := &maponv1.UnitGroup{}
grp.SetGroupId(g.ID)
grp.SetName(g.Name)
if g.ParentID != nil {
strVal := fmt.Sprintf("%v", g.ParentID)
if strVal != "" {
pid, _ := strconv.ParseInt(strVal, 10, 64)
grp.SetParentId(pid)
}
}
groups = append(groups, grp)
}
resp := &maponv1.ListUnitGroupsResponse{}
resp.SetGroups(groups)
return resp, nil
}
type jsonUnitGroupsResponse struct {
Data []struct {
ID int64 `json:"id"`
Name string `json:"name"`
ParentID interface{} `json:"parent_id"`
} `json:"data"`
Error *jsonError `json:"error"`
}