package home import ( "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" "strconv" ) func CategoryGets(c *gin.Context) { query := models.CategoryQuery{} if err := c.ShouldBind(&query); err != nil { logm.Get().Info(err.Error()) } db := dbm.Get().Model(&tables.Category{}) if len(query.Filters.Status) > 0 { db.Where("status IN ?", query.Filters.Status) } rows := []tables.Category{} if err := db.Order("sorter asc").Find(&rows).Error; err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusOK, gin.H{ "error": err.Error(), }) return } nested := make([]models.CategoryNested, 0) for _, row := range rows { if row.ID == query.Filters.ID { nested = append(nested, models.CategoryNested{ Category: row, }) break } } if len(nested) == 0 { nested = categoryChildren(rows, query.Filters.ID) } else if len(nested) == 1 { nested[0].Children = categoryChildren(rows, query.Filters.ID) } c.JSON(http.StatusOK, gin.H{ "error": nil, "rows": nested, }) } func categoryChildren(rows []tables.Category, parentID uint) []models.CategoryNested { children := make([]models.CategoryNested, 0) for _, row := range rows { if row.ParentID == parentID { item := models.CategoryNested{ Category: row, } item.Children = categoryChildren(rows, row.ID) children = append(children, item) } } return children } func CategoryGet(c *gin.Context) { id, err := strconv.Atoi(c.Query("id")) if err != nil { logm.Get().Info(err.Error()) c.JSON(http.StatusOK, gin.H{ "error": err.Error(), }) return } row := tables.Category{} if err := dbm.Get().Where("id=?", id).First(&row).Error; err != nil { logm.Get().Info(err.Error()) c.JSON(200, gin.H{ "error": err.Error(), }) return } c.JSON(http.StatusOK, gin.H{ "error": nil, "row": row, }) }