/
account.go
92 lines (78 loc) · 2.27 KB
/
account.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
package api
import (
"database/sql"
"github.com/fixcer/simplebank/api/model"
db "github.com/fixcer/simplebank/db/sqlc"
"github.com/fixcer/simplebank/token"
"github.com/gin-gonic/gin"
"github.com/lib/pq"
"github.com/pkg/errors"
"net/http"
)
func (server *Server) createAccount(ctx *gin.Context) {
var req model.CreateAccountRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
ctx.JSON(http.StatusBadRequest, ErrorResponse(err))
return
}
authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.CreateAccountParams{
Owner: authPayload.Username,
Currency: req.Currency,
Balance: 0,
}
account, err := server.store.CreateAccount(ctx, arg)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
switch pqErr.Code.Name() {
case "unique_violation", "foreign_key_violation":
ctx.JSON(http.StatusConflict, ErrorResponse(err))
return
}
}
ctx.JSON(http.StatusInternalServerError, ErrorResponse(err))
return
}
ctx.JSON(http.StatusOK, account)
}
func (server *Server) getAccount(ctx *gin.Context) {
var req model.GetAccountRequest
if err := ctx.ShouldBindUri(&req); err != nil {
ctx.JSON(http.StatusBadRequest, ErrorResponse(err))
return
}
account, err := server.store.GetAccount(ctx, req.ID)
if err != nil {
if err == sql.ErrNoRows {
ctx.JSON(http.StatusNotFound, ErrorResponse(err))
return
}
ctx.JSON(http.StatusInternalServerError, ErrorResponse(err))
return
}
authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
if account.Owner != authPayload.Username {
ctx.JSON(http.StatusForbidden, ErrorResponse(errors.New("you are not the owner of this account")))
return
}
ctx.JSON(http.StatusOK, account)
}
func (server *Server) listAccount(ctx *gin.Context) {
var req model.ListAccountRequest
if err := ctx.ShouldBindQuery(&req); err != nil {
ctx.JSON(http.StatusBadRequest, ErrorResponse(err))
return
}
authPayload := ctx.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.ListAccountsParams{
Owner: authPayload.Username,
Limit: req.PageSize,
Offset: (req.PageID - 1) * req.PageSize,
}
accounts, err := server.store.ListAccounts(ctx, arg)
if err != nil {
ctx.JSON(http.StatusInternalServerError, ErrorResponse(err))
return
}
ctx.JSON(http.StatusOK, accounts)
}