|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "encoding/json" |
| 6 | + "github.com/stretchr/objx" |
| 7 | +) |
| 8 | + |
| 9 | +// CurrentAccountUser spec |
| 10 | +type CurrentAccountUser struct { |
| 11 | + ID string |
| 12 | + UserName string |
| 13 | + Email string |
| 14 | +} |
| 15 | + |
| 16 | +// CurrentAccount spec |
| 17 | +type CurrentAccount struct { |
| 18 | + ID string |
| 19 | + Name string |
| 20 | + Users map[string]CurrentAccountUser |
| 21 | +} |
| 22 | + |
| 23 | +// GetCurrentAccount - |
| 24 | +func (client *Client) GetCurrentAccount() (*CurrentAccount, error) { |
| 25 | + |
| 26 | + // get and parse current account |
| 27 | + userResp, err := client.RequestAPI(&RequestOptions{ |
| 28 | + Path: "/user", |
| 29 | + Method: "GET", |
| 30 | + }) |
| 31 | + if err != nil { |
| 32 | + return nil, err |
| 33 | + } |
| 34 | + |
| 35 | + currentAccountX, err := objx.FromJSON(string(userResp)) |
| 36 | + if err != nil { |
| 37 | + return nil, err |
| 38 | + } |
| 39 | + |
| 40 | + activeAccountName := currentAccountX.Get("activeAccountName").String() |
| 41 | + if activeAccountName == "" { |
| 42 | + return nil, fmt.Errorf("GetCurrentAccount - cannot get activeAccountName") |
| 43 | + } |
| 44 | + currentAccount := &CurrentAccount{ |
| 45 | + Name: activeAccountName, |
| 46 | + Users: make(map[string]CurrentAccountUser), |
| 47 | + } |
| 48 | + |
| 49 | + allAccountsI := currentAccountX.Get("account").MSISlice() |
| 50 | + for _, accI := range(allAccountsI) { |
| 51 | + accX := objx.New(accI) |
| 52 | + if accX.Get("name").String() == activeAccountName { |
| 53 | + currentAccount.ID = accX.Get("id").String() |
| 54 | + break |
| 55 | + } |
| 56 | + } |
| 57 | + if currentAccount.ID == "" { |
| 58 | + return nil, fmt.Errorf("GetCurrentAccount - cannot get activeAccountName") |
| 59 | + } |
| 60 | + |
| 61 | + // get and parse account users |
| 62 | + accountUsersResp, err := client.RequestAPI(&RequestOptions{ |
| 63 | + Path: fmt.Sprintf("/accounts/%s/users", currentAccount.ID), |
| 64 | + Method: "GET", |
| 65 | + }) |
| 66 | + if err != nil { |
| 67 | + return nil, err |
| 68 | + } |
| 69 | + |
| 70 | + accountUsersI := make([]interface{}, 0) |
| 71 | + if e := json.Unmarshal(accountUsersResp, &accountUsersI); e != nil { |
| 72 | + return nil, fmt.Errorf("Cannot unmarshal accountUsers responce for accountId=%s: %v", currentAccount.ID, e) |
| 73 | + } |
| 74 | + for _, userI := range(accountUsersI) { |
| 75 | + userX := objx.New(userI) |
| 76 | + userName := userX.Get("userX").String() |
| 77 | + email := userX.Get("email").String() |
| 78 | + userID := userX.Get("_id").String() |
| 79 | + currentAccount.Users[userName] = CurrentAccountUser{ |
| 80 | + ID: userID, |
| 81 | + UserName: userName, |
| 82 | + Email: email, |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + return currentAccount, nil |
| 87 | +} |
0 commit comments