bbs-backend/logic/appservice/post_service.go

92 lines
2.1 KiB
Go
Raw Normal View History

2024-11-20 00:09:17 +08:00
// file name: post_service.go
2024-11-19 21:08:28 +08:00
package appservice
import (
"bbs-backend/api/request"
"bbs-backend/common/errcode"
2024-11-20 00:09:17 +08:00
"bbs-backend/dal"
2024-11-19 21:08:28 +08:00
"bbs-backend/dal/model"
"bbs-backend/logic/domainservice"
2024-11-20 00:09:17 +08:00
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"strings"
2024-11-19 21:08:28 +08:00
)
2024-11-20 00:09:17 +08:00
func CreatePost(c *gin.Context, req request.CreatePostRequest) (*model.Post, error) {
// 获取当前用户的 ID
userID, err := getUserIDFromToken(c)
if err != nil {
return nil, errcode.ErrUnauthorized
}
2024-11-19 21:08:28 +08:00
post := &model.Post{
2024-11-20 00:09:17 +08:00
Title: req.Title,
Content: req.Content,
AuthorID: userID,
CategoryID: req.CategoryID,
}
// 处理标签
var tags []model.Tag
for _, tagName := range req.Tags {
var tag model.Tag
// 检查标签是否存在,如果不存在则创建
if err := dal.DB.Where("name = ?", tagName).FirstOrCreate(&tag, model.Tag{Name: tagName}).Error; err != nil {
return nil, errcode.ErrInternalServerError
}
tags = append(tags, tag)
2024-11-19 21:08:28 +08:00
}
2024-11-20 00:09:17 +08:00
post.Tags = tags
2024-11-19 21:08:28 +08:00
2024-11-20 00:09:17 +08:00
err = domainservice.CreatePostDomainService(post)
2024-11-19 21:08:28 +08:00
if err != nil {
return nil, errcode.ErrInternalServerError
}
return post, nil
}
2024-11-20 00:09:17 +08:00
func getUserIDFromToken(c *gin.Context) (uint, error) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
return 0, errcode.ErrUnauthorized
}
tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte("your_secret_key"), nil
})
if err != nil {
return 0, errcode.ErrUnauthorized
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return 0, errcode.ErrUnauthorized
}
userID, ok := claims["user_id"].(float64)
if !ok {
return 0, errcode.ErrUnauthorized
}
return uint(userID), nil
}
2024-11-19 21:08:28 +08:00
func GetPost(postID uint) (*model.Post, error) {
post, err := domainservice.GetPostDomainService(postID)
if err != nil {
return nil, errcode.ErrNotFound
}
return post, nil
}
2024-11-20 00:09:17 +08:00
func GetPosts(req request.GetPostsRequest) ([]*model.Post, error) {
posts, err := domainservice.GetPostsDomainService(req)
2024-11-19 21:08:28 +08:00
if err != nil {
return nil, errcode.ErrInternalServerError
}
return posts, nil
}