/
user_handler.go
126 lines (109 loc) · 2.77 KB
/
user_handler.go
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package port
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/opendigitalpay-io/open-balance/internal/port/api"
"net/http"
)
func (h *HTTPServer) GetUserByID() func(ctx *gin.Context) {
return func(ctx *gin.Context) {
var uriParam api.GetUserUriParameter
err := ctx.ShouldBindUri(&uriParam)
if err != nil {
h.RespondWithError(ctx, err)
return
}
userID := uriParam.ID
user, err := h.userService.GetUser(ctx, userID)
if err != nil {
h.RespondWithError(ctx, err)
return
}
accounts, err := h.userService.GetVisibleBalanceAccounts(ctx, userID)
if err != nil {
h.RespondWithError(ctx, err)
return
}
var accountsResp []api.GetBalanceAccountResponse
for _, a := range accounts {
accountResp := api.GetBalanceAccountResponse{
Balance: a.Balance,
Currency: a.Currency,
Type: a.Type.String(),
State: a.State.String(),
Metadata: unmarshallMetadata(a.Metadata),
}
accountsResp = append(accountsResp, accountResp)
}
userResp := api.GetUserResponse{
ID: user.ID,
Email: user.Email,
Phone: user.Phone,
UserName: user.ExternalID,
Metadata: unmarshallMetadata(user.Metadata),
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
BalanceAccounts: accountsResp,
}
ctx.JSON(http.StatusOK, userResp)
}
}
func (h *HTTPServer) AddUser() func(ctx *gin.Context) {
return func(ctx *gin.Context) {
var req api.AddUserRequest
err := ctx.ShouldBindJSON(&req)
if err != nil {
h.RespondWithError(ctx, err)
return
}
user, err := h.userService.AddUser(ctx, req)
if err != nil {
h.RespondWithError(ctx, err)
return
}
resp := api.AddUserResponse{
ID: user.ID,
Email: user.Email,
Phone: user.Phone,
UserName: user.ExternalID,
CreatedAt: user.CreatedAt,
}
ctx.JSON(http.StatusOK, resp)
}
}
func (h *HTTPServer) UpdateUser() func(ctx *gin.Context) {
return func(ctx *gin.Context) {
var uriParam api.UpdateUserUriParameter
err := ctx.ShouldBindUri(&uriParam)
if err != nil {
h.RespondWithError(ctx, err)
return
}
var req api.UpdateUserRequest
err = ctx.ShouldBindJSON(&req)
if err != nil {
h.RespondWithError(ctx, err)
return
}
userID := uriParam.ID
user, err := h.userService.UpdateUser(ctx, userID, req)
if err != nil {
h.RespondWithError(ctx, err)
return
}
resp := api.UpdateUserResponse{
ID: user.ID,
Email: user.Email,
Phone: user.Phone,
UserName: user.ExternalID,
UpdatedAt: user.UpdatedAt,
}
ctx.JSON(http.StatusOK, resp)
}
}
// TODO this should be moved to utils
func unmarshallMetadata(bytes []byte) map[string]interface{} {
var metaData map[string]interface{}
json.Unmarshal(bytes, &metaData)
return metaData
}