package home import ( "fmt" "github.com/gin-gonic/gin" "github.com/han-joker/moo-layout/api/home/models" "github.com/han-joker/moo-layout/api/moo/dbm" "github.com/han-joker/moo-layout/api/moo/logm" "github.com/han-joker/moo-layout/api/tables" "net/http" "strings" ) const ( contentsLimit = 10 ) func ContentGets(c *gin.Context) { query := models.ContentsQuery{} if err := c.ShouldBind(&query); err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusOK, gin.H{ "error": err.Error(), }) return } rows := make([]tables.Content, 0) db := dbm.Get().Model(&tables.Content{}) db.Where("status=?", tables.ContentStatusPublish) if len(query.Filters.IDs) > 0 { db.Where("id IN ?", query.Filters.IDs) } if query.Filters.CategoryID != 0 { db.Where("category_id=?", query.Filters.CategoryID) } if len(query.Filters.Status) > 0 { db.Where("status IN ?", query.Filters.Status) } if len(query.Filters.Promotes) > 0 { pc := make([]string, len(query.Filters.Promotes)) pv := make([]interface{}, len(query.Filters.Promotes)) for i, p := range query.Filters.Promotes { pc[i] = "promotes & ? > 0" pv[i] = p } db.Where(strings.Join(pc, " OR "), pv...) } if query.Sorter.Field != "" && query.Sorter.Order != "" { db.Order(fmt.Sprintf("%s %s", query.Sorter.Field, models.OrderText[query.Sorter.Order])). Order("updated_at desc") } else { db.Order("updated_at desc") } db.Count(&query.Pagination.Total) if query.Pagination.PageSize > 0 { offset := (query.Pagination.Current - 1) * query.Pagination.PageSize db.Limit(query.Pagination.PageSize).Offset(offset) } db.Find(&rows) c.JSON(http.StatusOK, gin.H{ "error": nil, "rows": rows, "pagination": query.Pagination, "filters": query.Filters, "sorter": query.Sorter, }) } func ContentGet(c *gin.Context) { query := models.ContentQuery{} if err := c.ShouldBind(&query); err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusOK, gin.H{ "error": err.Error(), }) return } row := tables.Content{} if err := dbm.Get().Where("status=?", tables.ContentStatusPublish).Where("id=?", query.ID).First(&row).Error; err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusOK, gin.H{ "error": err.Error(), }) return } if query.WithCategory { dbm.Get().Model(&row).Association("Category").Find(&row.Category) } if query.WithUser { dbm.Get().Model(&row).Association("User").Find(&row.User) } c.JSON(http.StatusOK, gin.H{ "error": nil, "row": row, }) }