Advertisement
Gabsness

Codigo GO ( controller comment.go)

Mar 12th, 2019
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 3.63 KB | None | 0 0
  1. var Melody *melody.Melody
  2.  
  3. func init() {
  4.     Melody = melody.New()
  5. }
  6.  
  7. /* CreateComment: crea un comentario */
  8.  
  9. func CreateComment(w http.ResponseWriter, r *http.Request) {
  10.     m := models.Message{}
  11.     comment := models.Comment{}
  12.     user := models.User{}
  13.  
  14.  
  15.     user, _ = r.Context().Value("user").(models.User)
  16.  
  17.     err := json.NewDecoder(r.Body).Decode(&comment)
  18.  
  19.     if err != nil {
  20.         m.Code = http.StatusBadRequest
  21.         m.Message = fmt.Sprintf("Error al leer el comentario: %s", err)
  22.         commons.DisplayMessage(w, m)
  23.         return
  24.     }
  25.  
  26.     comment.UserID = user.ID
  27.  
  28.     db := configuration.GetConnection()
  29.     defer db.Close()
  30.  
  31.     err = db.Create(&comment).Error
  32.     if err != nil {
  33.         m.Code = http.StatusBadRequest
  34.         m.Message = fmt.Sprintf("Error al crear el comentario: %s", err)
  35.         commons.DisplayMessage(w, m)
  36.         return
  37.     }
  38.  
  39.     db.Model(&comment).Related(&comment.User)
  40.     comment.User[0].Password = ""
  41.  
  42.  
  43.     j, err := json.Marshal(&comment)
  44.     if err != nil {
  45.         m.Code = http.StatusInternalServerError
  46.         m.Message = fmt.Sprintf("no se pudo convertir a json: %s", err)
  47.         commons.DisplayMessage(w, m)
  48.         return
  49.     }
  50.  
  51.     origin := fmt.Sprintf("localhost:%d/", commons.Port)
  52.     url := fmt.Sprintf("ws://localhost:%d/ws", commons.Port)
  53.     ws , err := websocket.Dial(url, "", origin)
  54.     if err != nil {
  55.         log.Fatal(err)
  56.     }
  57.     if _, err := ws.Write(j); err != nil {
  58.         log.Fatal(err)
  59.     }
  60.     m.Code = http.StatusCreated
  61.     m.Message = "Comentario creado con éxito"
  62.     commons.DisplayMessage(w, m)
  63.     return
  64.  
  65. }
  66.  
  67. /* CommentGetAll: Obtiene todos los comentarios creados hasta ese momento */
  68.  
  69. func CommentGetAll(w http.ResponseWriter, r *http.Request) {
  70.     comments := []models.Comment{}
  71.     m := models.Message{}
  72.     user := models.User{}
  73.     vote := models.Vote{}
  74.  
  75.     user , _ = r.Context().Value("user").(models.User)
  76.     /*vars_todo lo que llegue despues del ? en la api*/
  77.     vars := r.URL.Query()
  78.  
  79.     db := configuration.GetConnection()
  80.     defer db.Close()
  81.  
  82.     cComments := db.Where("parent_id = 0")
  83.     if order, ok := vars["order"]; ok {
  84.         if order[0] == "votes" {
  85.             cComments = cComments.Order("votes desc, created_at desc")
  86.  
  87.         }
  88.     } else {
  89.  
  90.         if idlimit, ok := vars["idlimit"]; ok {
  91.             registerByPage := 30
  92.             offset, err := strconv.Atoi(idlimit[0])
  93.             if err != nil {
  94.                 log.Println("Error: ", err)
  95.             }
  96.             cComments = cComments.Where("id BETWEEN ? AND ?", offset-registerByPage, offset)
  97.         }
  98.         cComments = cComments.Order("id desc")
  99.     }
  100.  
  101.     cComments.Find(&comments)
  102.  
  103.     for i := range comments {
  104.         db.Model(&comments[i]).Related(&comments[i].User)
  105.         comments[i].User[0].Password = ""
  106.         comments[i].Children = commentGetChildren(comments[i].ID)
  107.  
  108.         /* Se busca el voto del usuario en Sesión */
  109.  
  110.         vote.CommentID = comments[i].ID
  111.         vote.UserID = user.ID
  112.         count := db.Where(&vote).Find(&vote).RowsAffected
  113.         if count > 0 {
  114.             if vote.Value {
  115.                 comments[i].HasVote = 1
  116.             } else {
  117.                 comments[i].HasVote = -1
  118.             }
  119.         }
  120.     }
  121.  
  122.     j,err := json.Marshal(comments)
  123.     if err != nil {
  124.         m.Code = http.StatusInternalServerError
  125.         m.Message = "Error al convertir los mensajes en formato json"
  126.         commons.DisplayMessage(w, m)
  127.         return
  128.     }
  129.  
  130.     if len(comments) > 0 {
  131.         w.Header().Set("Content-Type", "application/json")
  132.         w.WriteHeader(http.StatusOK)
  133.         w.Write(j)
  134.     } else {
  135.         m.Code = http.StatusNoContent
  136.         m.Message = "No hay contenido de comentarios"
  137.         commons.DisplayMessage(w,m)
  138.     }
  139. }
  140.  
  141. func commentGetChildren(id uint) (children []models.Comment) {
  142.     db := configuration.GetConnection()
  143.     defer db.Close()
  144.  
  145.     db.Where("parent_id = ? ", id).Find(&children)
  146.  
  147.     for i := range children {
  148.         db.Model(&children[i]).Related(&children[i].User)
  149.         children[i].User[0].Password = ""
  150.     }
  151.     return
  152. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement