blog/internal/controller/adm_controller/diary_controller.go

96 lines
2.3 KiB
Go

package adm_controller
import (
"Blog/internal/client"
"Blog/internal/consts"
"Blog/internal/model"
"Blog/internal/model/result"
"Blog/internal/repository"
"Blog/internal/service"
"Blog/internal/utils"
"context"
"net/http"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"github.com/kataras/iris/v12/sessions"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
/*
日记管理
*/
type DiaryController struct {
Ctx iris.Context
Session *sessions.Session
}
func (ctrl *DiaryController) Get() {
ctrl.Ctx.View("/admin/diary/index.html")
}
func (ctrl *DiaryController) PostSubmit() {
user := utils.SessionUtil.GetUser(ctrl.Session)
createBy := user.Username
content := ctrl.Ctx.FormValue("content")
_, headers, fileErr := ctrl.Ctx.FormFiles("file")
if fileErr != nil {
logrus.Error("日记文件表单异常", fileErr)
ctrl.Ctx.JSON(result.Error("发布失败,日记文件表单异常"))
return
}
diary := service.DiaryService.SaveDiary(content, createBy, headers)
if diary == nil {
logrus.Error("日记发布失败")
ctrl.Ctx.JSON(result.Error("日记发布失败"))
return
}
ctrl.Ctx.JSON(result.OkMsg("发布成功", nil))
}
func (ctrl *DiaryController) DelDiary() {
id := ctrl.Ctx.Params().Get("id")
if id == "" {
ctrl.Ctx.JSON(result.Error("ID为空"))
return
}
logrus.Info("删除日记==>", id)
ctx := context.Background()
err := repository.DiaryRepository().WGorm(func(tx *gorm.DB) error {
var txErr error
txErr = tx.Table(consts.TABLE_BLOG_DIARY).Unscoped().Delete(&model.BlogDiary{Id: id}).Error
if txErr != nil {
return txErr
}
txErr = tx.Table(consts.TABLE_BLOG_TEXT_CONTENT).Unscoped().Where("rel_id = ?", id).Delete(&model.BlogTextContent{}).Error
if txErr != nil {
return txErr
}
client.RedisClient().Del(ctx, consts.REDIS_BLOG_DIARY+id, consts.REDIS_BLOG_CONTENT+id).Err()
return txErr
})
if err == nil {
service.DiaryService.RefreshLatest()
}
if err != nil {
ctrl.Ctx.JSON(result.Error("删除失败"))
}
ctrl.Ctx.JSON(result.OkMsg("删除完成", nil))
}
func (ctrl *DiaryController) BeforeActivation(activation mvc.BeforeActivation) {
// logrus.Info("before")
activation.Handle(http.MethodDelete, "/del/{id}", "DelDiary")
}
func (ctrl *DiaryController) AfterActivation(activation mvc.AfterActivation) {
// logrus.Info("after")
}