package category import ( "fmt" "github.com/gin-gonic/gin" "net/http" "product/backend/module/base" "product/backend/moo/db" "product/backend/moo/log" ) func Post(ctx *gin.Context) { row := &PostModel{} if err := ctx.ShouldBind(&row); err != nil { log.Error(err) ctx.JSON(http.StatusOK, gin.H{ "code": 1, "errors": base.Translate(err), }) return } if result := db.DB.Create(row); result.Error != nil { log.Error(result.Error) ctx.JSON(http.StatusOK, gin.H{ "code": 1, }) return } // response ctx.JSON(http.StatusOK, gin.H{ "code": 0, "data": gin.H{ "row": row, }, }) } func Put(ctx *gin.Context) { row := &PutModel{} if err := ctx.ShouldBind(&row); err != nil { log.Error(err) ctx.JSON(http.StatusOK, gin.H{ "code": 1, "errors": base.Translate(err), }) return } if result := db.DB.Updates(row); result.Error != nil { log.Error(result.Error) ctx.JSON(http.StatusOK, gin.H{ "code": 1, }) return } // 查询记录 db.DB.First(row) // response ctx.JSON(http.StatusOK, gin.H{ "code": 0, "data": gin.H{ "row": row, }, }) } func Delete(ctx *gin.Context) { id := ctx.QueryArray("id") if result := db.DB.Delete(&Model{}, id); result.Error != nil { log.Error(result.Error) ctx.JSON(http.StatusOK, gin.H{ "code": 1, }) return } // response ctx.JSON(http.StatusOK, gin.H{ "code": 0, }) } func Get(ctx *gin.Context) { // get request param req := &GetReq{} if err := req.Init(ctx); err != nil { log.Error(err) ctx.JSON(http.StatusOK, gin.H{ "code": 1, }) return } // init query query := db.DB.Model(&Model{}) if req.ID == 0 { // list // filter // keyword if req.Keyword != "" { query.Where("title LIKE ?", req.Keyword+"%") } // total var total int64 query.Count(&total) // order query.Order(fmt.Sprintf("%s %s", req.SortField, req.SortOrder)) // # offset limit offset := -1 // 不限制 if req.PageSize > 0 { offset = (req.PageIndex - 1) * req.PageSize } query.Offset(offset).Limit(req.PageSize) // select query.Select("*") // fetch var rows []*Model if result := query.Find(&rows); result.Error != nil { log.Error(result.Error) ctx.JSON(http.StatusOK, gin.H{ "code": 1, }) return } // response ctx.JSON(http.StatusOK, gin.H{ "code": 0, "data": gin.H{ "list": rows, "total": total, "keyword": req.Keyword, "pageIndex": req.PageIndex, "pageSize": req.PageSize, "sortField": req.SortField, "sortOrder": req.SortOrder, }, }) } else { // one // fetch var row *Model if result := query.First(&row, req.ID); result.Error != nil { log.Error(result.Error) ctx.JSON(http.StatusOK, gin.H{ "code": 1, }) return } // response ctx.JSON(http.StatusOK, gin.H{ "code": 0, "data": gin.H{ "row": row, }, }) } }