92 lines
2.1 KiB
Go
92 lines
2.1 KiB
Go
// file name: post_service.go
|
|
package appservice
|
|
|
|
import (
|
|
"bbs-backend/api/request"
|
|
"bbs-backend/common/errcode"
|
|
"bbs-backend/dal"
|
|
"bbs-backend/dal/model"
|
|
"bbs-backend/logic/domainservice"
|
|
"github.com/dgrijalva/jwt-go"
|
|
"github.com/gin-gonic/gin"
|
|
"strings"
|
|
)
|
|
|
|
func CreatePost(c *gin.Context, req request.CreatePostRequest) (*model.Post, error) {
|
|
// 获取当前用户的 ID
|
|
userID, err := getUserIDFromToken(c)
|
|
if err != nil {
|
|
return nil, errcode.ErrUnauthorized
|
|
}
|
|
|
|
post := &model.Post{
|
|
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)
|
|
}
|
|
post.Tags = tags
|
|
|
|
err = domainservice.CreatePostDomainService(post)
|
|
if err != nil {
|
|
return nil, errcode.ErrInternalServerError
|
|
}
|
|
|
|
return post, nil
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func GetPost(postID uint) (*model.Post, error) {
|
|
post, err := domainservice.GetPostDomainService(postID)
|
|
if err != nil {
|
|
return nil, errcode.ErrNotFound
|
|
}
|
|
return post, nil
|
|
}
|
|
|
|
func GetPosts(req request.GetPostsRequest) ([]*model.Post, error) {
|
|
posts, err := domainservice.GetPostsDomainService(req)
|
|
if err != nil {
|
|
return nil, errcode.ErrInternalServerError
|
|
}
|
|
return posts, nil
|
|
}
|