relation.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package controller
  2. import (
  3. "github.com/RaymondCode/simple-demo/api"
  4. "github.com/RaymondCode/simple-demo/dao"
  5. "github.com/RaymondCode/simple-demo/entities"
  6. "github.com/RaymondCode/simple-demo/service"
  7. "github.com/gin-gonic/gin"
  8. "net/http"
  9. "strings"
  10. )
  11. type UserListResponse struct {
  12. api.Response
  13. UserList []api.User `json:"user_list"`
  14. }
  15. // RelationAction no practical effect, just check if token is valid
  16. // 三个参数,token,to_user_id,action_type(1-关注,2-取消关注)
  17. func RelationAction(c *gin.Context) {
  18. token := c.Query("token")
  19. action_type := c.Query("action_type")
  20. to_user_id := c.Query("to_user_id")
  21. if res, _ := service.GetToken(token); res == 0 {
  22. from_user_id := dao.GetIdByUserId(strings.Split(token, ":")[0])
  23. if from_user_id == to_user_id {
  24. c.JSON(http.StatusOK, api.Response{StatusCode: 1, StatusMsg: "Can not follow self"})
  25. return
  26. }
  27. service.AddNewFollowRelation(from_user_id, to_user_id, action_type)
  28. c.JSON(http.StatusOK, api.Response{StatusCode: 0})
  29. } else {
  30. c.JSON(http.StatusOK, api.Response{StatusCode: 1, StatusMsg: "User doesn't exist"})
  31. }
  32. }
  33. // FollowList all users have same follow list
  34. func FollowList(c *gin.Context) {
  35. id := c.Query("user_id")
  36. userIdList := service.GetFollowList(id)
  37. userList := dao.GetUserListByIdArray(userIdList)
  38. res := transUserList(userList)
  39. c.JSON(http.StatusOK, UserListResponse{
  40. Response: api.Response{
  41. StatusCode: 0,
  42. },
  43. UserList: res,
  44. })
  45. }
  46. // FollowerList all users have same follower list
  47. func FollowerList(c *gin.Context) {
  48. id := c.Query("user_id")
  49. userIdList := service.GetFollowerList(id)
  50. userList := dao.GetUserListByIdArray(userIdList)
  51. res := transUserList(userList)
  52. c.JSON(http.StatusOK, UserListResponse{
  53. Response: api.Response{
  54. StatusCode: 0,
  55. },
  56. UserList: res,
  57. })
  58. }
  59. func transUserList(userList []entities.User) []api.User {
  60. var res []api.User
  61. for i := 0; i < len(userList); i++ {
  62. res = append(res, api.User{
  63. Id: userList[i].Id,
  64. Name: userList[i].Name,
  65. FollowCount: userList[i].FollowCount,
  66. FollowerCount: userList[i].FollowerCount,
  67. IsFollow: userList[i].IsFollow,
  68. })
  69. }
  70. return res
  71. }