|
| 1 | +package users |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strconv" |
| 6 | + |
| 7 | + "github.com/gin-gonic/gin" |
| 8 | + "github.com/gin-gonic/gin/binding" |
| 9 | + "go.uber.org/zap" |
| 10 | + |
| 11 | + gb "github.com/gitploy-io/gitploy/internal/server/global" |
| 12 | + "github.com/gitploy-io/gitploy/pkg/e" |
| 13 | +) |
| 14 | + |
| 15 | +type ( |
| 16 | + userPatchPayload struct { |
| 17 | + Admin *bool `json:"admin"` |
| 18 | + } |
| 19 | +) |
| 20 | + |
| 21 | +func (u *UserAPI) Update(c *gin.Context) { |
| 22 | + ctx := c.Request.Context() |
| 23 | + |
| 24 | + var ( |
| 25 | + id int64 |
| 26 | + err error |
| 27 | + ) |
| 28 | + |
| 29 | + if id, err = strconv.ParseInt(c.Param("id"), 10, 64); err != nil { |
| 30 | + u.log.Warn("The id must be number.", zap.Error(err)) |
| 31 | + gb.ResponseWithError( |
| 32 | + c, |
| 33 | + e.NewErrorWithMessage(e.ErrorCodeParameterInvalid, "The id must be number.", err), |
| 34 | + ) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + p := &userPatchPayload{} |
| 39 | + if err := c.ShouldBindBodyWith(p, binding.JSON); err != nil { |
| 40 | + u.log.Warn("It has failed to binding the payload.", zap.Error(err)) |
| 41 | + gb.ResponseWithError( |
| 42 | + c, |
| 43 | + e.NewErrorWithMessage(e.ErrorCodeParameterInvalid, "It has failed to binding the payload.", err), |
| 44 | + ) |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + du, err := u.i.FindUserByID(ctx, id) |
| 49 | + if err != nil { |
| 50 | + u.log.Check(gb.GetZapLogLevel(err), "Failed to find the user.").Write(zap.Error(err)) |
| 51 | + gb.ResponseWithError(c, err) |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + if p.Admin != nil { |
| 56 | + du.Admin = *p.Admin |
| 57 | + if du, err = u.i.UpdateUser(ctx, du); err != nil { |
| 58 | + u.log.Check(gb.GetZapLogLevel(err), "Failed to update the user.").Write(zap.Error(err)) |
| 59 | + gb.ResponseWithError(c, err) |
| 60 | + return |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + gb.Response(c, http.StatusOK, du) |
| 65 | +} |
0 commit comments