|
| 1 | +package v1 |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/labstack/echo/v4" |
| 5 | + "github.com/neatplex/nightel-core/internal/models" |
| 6 | + "github.com/neatplex/nightel-core/internal/services/container" |
| 7 | + "net/http" |
| 8 | +) |
| 9 | + |
| 10 | +type LikesStoreRequest struct { |
| 11 | + StoryID uint64 `json:"story_id" validate:"required"` |
| 12 | +} |
| 13 | + |
| 14 | +func LikesStore(ctr *container.Container) echo.HandlerFunc { |
| 15 | + return func(ctx echo.Context) error { |
| 16 | + user := ctx.Get("user").(*models.User) |
| 17 | + |
| 18 | + var r LikesStoreRequest |
| 19 | + if err := ctx.Bind(&r); err != nil { |
| 20 | + return ctx.JSON(http.StatusBadRequest, map[string]string{ |
| 21 | + "message": "Cannot parse the request body.", |
| 22 | + }) |
| 23 | + } |
| 24 | + if err := ctx.Validate(r); err != nil { |
| 25 | + return ctx.JSON(http.StatusUnprocessableEntity, map[string]string{ |
| 26 | + "message": err.Error(), |
| 27 | + }) |
| 28 | + } |
| 29 | + |
| 30 | + story, err := ctr.StoryService.FindById(r.StoryID) |
| 31 | + if err != nil { |
| 32 | + return err |
| 33 | + } |
| 34 | + |
| 35 | + like, err := ctr.LikeService.Create(user, story) |
| 36 | + if err != nil { |
| 37 | + return err |
| 38 | + } |
| 39 | + |
| 40 | + return ctx.JSON(http.StatusCreated, map[string]*models.Like{ |
| 41 | + "like": like, |
| 42 | + }) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +type LikesDeleteRequest struct { |
| 47 | + LikeID uint64 `json:"like_id" validate:"required"` |
| 48 | +} |
| 49 | + |
| 50 | +func LikesDelete(ctr *container.Container) echo.HandlerFunc { |
| 51 | + return func(ctx echo.Context) error { |
| 52 | + user := ctx.Get("user").(*models.User) |
| 53 | + |
| 54 | + var r LikesDeleteRequest |
| 55 | + if err := ctx.Bind(&r); err != nil { |
| 56 | + return ctx.JSON(http.StatusBadRequest, map[string]string{ |
| 57 | + "message": "Cannot parse the request body.", |
| 58 | + }) |
| 59 | + } |
| 60 | + if err := ctx.Validate(r); err != nil { |
| 61 | + return ctx.JSON(http.StatusUnprocessableEntity, map[string]string{ |
| 62 | + "message": err.Error(), |
| 63 | + }) |
| 64 | + } |
| 65 | + |
| 66 | + like, err := ctr.LikeService.FindById(r.LikeID) |
| 67 | + if err != nil { |
| 68 | + return err |
| 69 | + } |
| 70 | + |
| 71 | + if like.UserID != user.ID { |
| 72 | + return ctx.JSON(http.StatusForbidden, map[string]string{ |
| 73 | + "message": "You do not have permission to perform this action.", |
| 74 | + }) |
| 75 | + } |
| 76 | + |
| 77 | + if err = ctr.LikeService.Delete(like.ID); err != nil { |
| 78 | + return err |
| 79 | + } |
| 80 | + |
| 81 | + return ctx.NoContent(http.StatusNoContent) |
| 82 | + } |
| 83 | +} |
0 commit comments