|
| 1 | +package controller |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strconv" |
| 6 | + |
| 7 | + "github.com/Lab-RPL-ITS/twitter-clone-api/dto" |
| 8 | + "github.com/Lab-RPL-ITS/twitter-clone-api/service" |
| 9 | + "github.com/Lab-RPL-ITS/twitter-clone-api/utils" |
| 10 | + "github.com/gin-gonic/gin" |
| 11 | +) |
| 12 | + |
| 13 | +type ( |
| 14 | + LikesController interface { |
| 15 | + LikePostById(ctx *gin.Context) |
| 16 | + UnlikePostById(ctx *gin.Context) |
| 17 | + } |
| 18 | + |
| 19 | + likesController struct { |
| 20 | + likesService service.LikesService |
| 21 | + } |
| 22 | +) |
| 23 | + |
| 24 | +func NewLikesController(likesService service.LikesService) LikesController { |
| 25 | + return &likesController{ |
| 26 | + likesService: likesService, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func (c *likesController) LikePostById(ctx *gin.Context) { |
| 31 | + postId := ctx.Param("post_id") |
| 32 | + userId := ctx.GetString("user_id") |
| 33 | + |
| 34 | + postIdUint, err := strconv.ParseUint(postId, 10, 64) |
| 35 | + if err != nil { |
| 36 | + response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_GET_POST_ID, err.Error(), nil) |
| 37 | + ctx.JSON(http.StatusBadRequest, response) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + err = c.likesService.LikePostById(ctx, postIdUint, userId) |
| 42 | + if err != nil { |
| 43 | + response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_LIKE_POST, err.Error(), nil) |
| 44 | + ctx.JSON(http.StatusBadRequest, response) |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + response := utils.BuildResponseSuccess(dto.MESSAGE_SUCCESS_LIKE_POST, nil) |
| 49 | + ctx.JSON(http.StatusOK, response) |
| 50 | +} |
| 51 | + |
| 52 | +func (c *likesController) UnlikePostById(ctx *gin.Context) { |
| 53 | + postId := ctx.Param("post_id") |
| 54 | + userId := ctx.GetString("user_id") |
| 55 | + |
| 56 | + postIdUint, err := strconv.ParseUint(postId, 10, 64) |
| 57 | + if err != nil { |
| 58 | + response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_GET_POST_ID, err.Error(), nil) |
| 59 | + ctx.JSON(http.StatusBadRequest, response) |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + err = c.likesService.UnLikePostById(ctx, postIdUint, userId) |
| 64 | + if err != nil { |
| 65 | + response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_UNLIKE_POST, err.Error(), nil) |
| 66 | + ctx.JSON(http.StatusBadRequest, response) |
| 67 | + return |
| 68 | + } |
| 69 | + |
| 70 | + response := utils.BuildResponseSuccess(dto.MESSAGE_SUCCESS_UNLIKE_POST, nil) |
| 71 | + ctx.JSON(http.StatusOK, response) |
| 72 | +} |
0 commit comments