optimize #97 user stars/collections update when post visibility changed

pull/106/head
alimy 3 years ago
parent 7e5d1540e0
commit 0da2c76d0b

@ -77,8 +77,8 @@ LocalOSS: # 本地文件OSS存储配置
Bucket: paopao Bucket: paopao
Domain: 127.0.0.1:8008 Domain: 127.0.0.1:8008
Database: # Database通用配置 Database: # Database通用配置
LogLevel: 2 LogLevel: error # 日志级别 silent|error|warn|info
TablePrefix: p_ TablePrefix: p_ # 表名前缀
MySQL: # MySQL数据库 MySQL: # MySQL数据库
Username: paopao Username: paopao
Password: paopao Password: paopao
@ -88,7 +88,7 @@ MySQL: # MySQL数据库
ParseTime: True ParseTime: True
MaxIdleConns: 10 MaxIdleConns: 10
MaxOpenConns: 30 MaxOpenConns: 30
Postgres: Postgres: # PostgreSQL数据库
User: paopao User: paopao
Password: paopao Password: paopao
DBName: paopao DBName: paopao

@ -23,10 +23,10 @@ func newDBEngine() (*gorm.DB, error) {
newLogger := logger.New( newLogger := logger.New(
logrus.StandardLogger(), // io writer日志输出的目标前缀和日志包含的内容 logrus.StandardLogger(), // io writer日志输出的目标前缀和日志包含的内容
logger.Config{ logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值 SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: databaseSetting.LogLevel, // 日志级别 LogLevel: databaseSetting.logLevel(), // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误 IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: false, // 禁用彩色打印 Colorful: false, // 禁用彩色打印
}, },
) )

@ -80,7 +80,7 @@ type ZincSettingS struct {
type DatabaseSetingS struct { type DatabaseSetingS struct {
TablePrefix string TablePrefix string
LogLevel logger.LogLevel LogLevel string
} }
type MySQLSettingS struct { type MySQLSettingS struct {
@ -282,3 +282,18 @@ func (s PostgresSettingS) Dsn() string {
} }
return strings.Join(params, " ") return strings.Join(params, " ")
} }
func (s *DatabaseSetingS) logLevel() logger.LogLevel {
switch strings.ToLower(s.LogLevel) {
case "silent":
return logger.Silent
case "error":
return logger.Error
case "warn":
return logger.Warn
case "info":
return logger.Info
default:
return logger.Error
}
}

@ -120,7 +120,7 @@ func (d *dataServant) GetUserPostStars(userID int64, offset, limit int) ([]*mode
} }
return star.List(d.engine, &model.ConditionsT{ return star.List(d.engine, &model.ConditionsT{
"ORDER": "id DESC", "ORDER": d.engine.NamingStrategy.TableName("PostStar") + ".id DESC",
}, offset, limit) }, offset, limit)
} }
@ -159,7 +159,7 @@ func (d *dataServant) GetUserPostCollections(userID int64, offset, limit int) ([
} }
return collection.List(d.engine, &model.ConditionsT{ return collection.List(d.engine, &model.ConditionsT{
"ORDER": "id DESC", "ORDER": d.engine.NamingStrategy.TableName("PostCollection") + ".id DESC",
}, offset, limit) }, offset, limit)
} }

@ -8,22 +8,26 @@ import (
type PostCollection struct { type PostCollection struct {
*Model *Model
Post *Post `json:"-"`
PostID int64 `json:"post_id"` PostID int64 `json:"post_id"`
UserID int64 `json:"user_id"` UserID int64 `json:"user_id"`
} }
func (p *PostCollection) Get(db *gorm.DB) (*PostCollection, error) { func (p *PostCollection) Get(db *gorm.DB) (*PostCollection, error) {
var star PostCollection var star PostCollection
tn := db.NamingStrategy.TableName("PostCollection") + "."
if p.Model != nil && p.ID > 0 { if p.Model != nil && p.ID > 0 {
db = db.Where("id = ? AND is_del = ?", p.ID, 0) db = db.Where(tn+"id = ? AND "+tn+"is_del = ?", p.ID, 0)
} }
if p.PostID > 0 { if p.PostID > 0 {
db = db.Where("post_id = ?", p.PostID) db = db.Where(tn+"post_id = ?", p.PostID)
} }
if p.UserID > 0 { if p.UserID > 0 {
db = db.Where("user_id = ?", p.UserID) db = db.Where(tn+"user_id = ?", p.UserID)
} }
db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC")
err := db.First(&star).Error err := db.First(&star).Error
if err != nil { if err != nil {
return &star, err return &star, err
@ -33,13 +37,13 @@ func (p *PostCollection) Get(db *gorm.DB) (*PostCollection, error) {
} }
func (p *PostCollection) Create(db *gorm.DB) (*PostCollection, error) { func (p *PostCollection) Create(db *gorm.DB) (*PostCollection, error) {
err := db.Create(&p).Error err := db.Omit("Post").Create(&p).Error
return p, err return p, err
} }
func (p *PostCollection) Delete(db *gorm.DB) error { func (p *PostCollection) Delete(db *gorm.DB) error {
return db.Model(&PostCollection{}).Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]interface{}{ return db.Model(&PostCollection{}).Omit("Post").Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]interface{}{
"deleted_on": time.Now().Unix(), "deleted_on": time.Now().Unix(),
"is_del": 1, "is_del": 1,
}).Error }).Error
@ -48,22 +52,25 @@ func (p *PostCollection) Delete(db *gorm.DB) error {
func (p *PostCollection) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostCollection, error) { func (p *PostCollection) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostCollection, error) {
var collections []*PostCollection var collections []*PostCollection
var err error var err error
tn := db.NamingStrategy.TableName("PostCollection") + "."
if offset >= 0 && limit > 0 { if offset >= 0 && limit > 0 {
db = db.Offset(offset).Limit(limit) db = db.Offset(offset).Limit(limit)
} }
if p.UserID > 0 { if p.UserID > 0 {
db = db.Where("user_id = ?", p.UserID) db = db.Where(tn+"user_id = ?", p.UserID)
} }
for k, v := range *conditions { for k, v := range *conditions {
if k == "ORDER" { if k == "ORDER" {
db = db.Order(v) db = db.Order(v)
} else { } else {
db = db.Where(k, v) db = db.Where(tn+k, v)
} }
} }
if err = db.Where("is_del = ?", 0).Find(&collections).Error; err != nil { db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC")
if err = db.Where(tn+"is_del = ?", 0).Find(&collections).Error; err != nil {
return nil, err return nil, err
} }
@ -72,17 +79,21 @@ func (p *PostCollection) List(db *gorm.DB, conditions *ConditionsT, offset, limi
func (p *PostCollection) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { func (p *PostCollection) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) {
var count int64 var count int64
tn := db.NamingStrategy.TableName("PostCollection") + "."
if p.PostID > 0 { if p.PostID > 0 {
db = db.Where("post_id = ?", p.PostID) db = db.Where(tn+"post_id = ?", p.PostID)
} }
if p.UserID > 0 { if p.UserID > 0 {
db = db.Where("user_id = ?", p.UserID) db = db.Where(tn+"user_id = ?", p.UserID)
} }
for k, v := range *conditions { for k, v := range *conditions {
if k != "ORDER" { if k != "ORDER" {
db = db.Where(k, v) db = db.Where(tn+k, v)
} }
} }
db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate)
if err := db.Model(p).Count(&count).Error; err != nil { if err := db.Model(p).Count(&count).Error; err != nil {
return 0, err return 0, err
} }

@ -8,38 +8,40 @@ import (
type PostStar struct { type PostStar struct {
*Model *Model
Post *Post `json:"-"`
PostID int64 `json:"post_id"` PostID int64 `json:"post_id"`
UserID int64 `json:"user_id"` UserID int64 `json:"user_id"`
} }
func (p *PostStar) Get(db *gorm.DB) (*PostStar, error) { func (p *PostStar) Get(db *gorm.DB) (*PostStar, error) {
var star PostStar var star PostStar
tn := db.NamingStrategy.TableName("PostStar") + "."
if p.Model != nil && p.ID > 0 { if p.Model != nil && p.ID > 0 {
db = db.Where("id = ? AND is_del = ?", p.ID, 0) db = db.Where(tn+"id = ? AND "+tn+"is_del = ?", p.ID, 0)
} }
if p.PostID > 0 { if p.PostID > 0 {
db = db.Where("post_id = ?", p.PostID) db = db.Where(tn+"post_id = ?", p.PostID)
} }
if p.UserID > 0 { if p.UserID > 0 {
db = db.Where("user_id = ?", p.UserID) db = db.Where(tn+"user_id = ?", p.UserID)
} }
err := db.First(&star).Error db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC")
if err != nil { if err := db.First(&star).Error; err != nil {
return &star, err return nil, err
} }
return &star, nil return &star, nil
} }
func (p *PostStar) Create(db *gorm.DB) (*PostStar, error) { func (p *PostStar) Create(db *gorm.DB) (*PostStar, error) {
err := db.Create(&p).Error err := db.Omit("Post").Create(&p).Error
return p, err return p, err
} }
func (p *PostStar) Delete(db *gorm.DB) error { func (p *PostStar) Delete(db *gorm.DB) error {
return db.Model(&PostStar{}).Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]interface{}{ return db.Model(&PostStar{}).Omit("Post").Where("id = ? AND is_del = ?", p.Model.ID, 0).Updates(map[string]interface{}{
"deleted_on": time.Now().Unix(), "deleted_on": time.Now().Unix(),
"is_del": 1, "is_del": 1,
}).Error }).Error
@ -48,44 +50,49 @@ func (p *PostStar) Delete(db *gorm.DB) error {
func (p *PostStar) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostStar, error) { func (p *PostStar) List(db *gorm.DB, conditions *ConditionsT, offset, limit int) ([]*PostStar, error) {
var stars []*PostStar var stars []*PostStar
var err error var err error
tn := db.NamingStrategy.TableName("PostStar") + "."
if offset >= 0 && limit > 0 { if offset >= 0 && limit > 0 {
db = db.Offset(offset).Limit(limit) db = db.Offset(offset).Limit(limit)
} }
if p.UserID > 0 { if p.UserID > 0 {
db = db.Where("user_id = ?", p.UserID) db = db.Where(tn+"user_id = ?", p.UserID)
} }
for k, v := range *conditions { for k, v := range *conditions {
if k == "ORDER" { if k == "ORDER" {
db = db.Order(v) db = db.Order(v)
} else { } else {
db = db.Where(k, v) db = db.Where(tn+k, v)
} }
} }
if err = db.Where("is_del = ?", 0).Find(&stars).Error; err != nil { db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate).Order("Post.id DESC")
if err = db.Find(&stars).Error; err != nil {
return nil, err return nil, err
} }
return stars, nil return stars, nil
} }
func (p *PostStar) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) { func (p *PostStar) Count(db *gorm.DB, conditions *ConditionsT) (int64, error) {
var count int64 var count int64
tn := db.NamingStrategy.TableName("PostStar") + "."
if p.PostID > 0 { if p.PostID > 0 {
db = db.Where("post_id = ?", p.PostID) db = db.Where(tn+"post_id = ?", p.PostID)
} }
if p.UserID > 0 { if p.UserID > 0 {
db = db.Where("user_id = ?", p.UserID) db = db.Where(tn+"user_id = ?", p.UserID)
} }
for k, v := range *conditions { for k, v := range *conditions {
if k != "ORDER" { if k != "ORDER" {
db = db.Where(k, v) db = db.Where(tn+k, v)
} }
} }
db = db.Joins("Post").Where("Post.visibility <> ?", PostVisitPrivate)
if err := db.Model(p).Count(&count).Error; err != nil { if err := db.Model(p).Count(&count).Error; err != nil {
return 0, err return 0, err
} }
return count, nil return count, nil
} }

@ -156,11 +156,16 @@ func PostStar(c *gin.Context) {
star, err := service.GetPostStar(param.ID, userID.(int64)) star, err := service.GetPostStar(param.ID, userID.(int64))
if err != nil { if err != nil {
// 创建Star // 创建Star
service.CreatePostStar(param.ID, userID.(int64)) _, err = service.CreatePostStar(param.ID, userID.(int64))
status = true status = true
} else { } else {
// 取消Star // 取消Star
service.DeletePostStar(star) err = service.DeletePostStar(star)
}
if err != nil {
response.ToErrorResponse(errcode.NoPermission)
return
} }
response.ToResponse(gin.H{ response.ToResponse(gin.H{
@ -204,11 +209,16 @@ func PostCollection(c *gin.Context) {
collection, err := service.GetPostCollection(param.ID, userID.(int64)) collection, err := service.GetPostCollection(param.ID, userID.(int64))
if err != nil { if err != nil {
// 创建collection // 创建collection
service.CreatePostCollection(param.ID, userID.(int64)) _, err = service.CreatePostCollection(param.ID, userID.(int64))
status = true status = true
} else { } else {
// 取消Star // 取消Star
service.DeletePostCollection(collection) err = service.DeletePostCollection(collection)
}
if err != nil {
response.ToErrorResponse(errcode.NoPermission)
return
} }
response.ToResponse(gin.H{ response.ToResponse(gin.H{

@ -2,6 +2,7 @@ package service
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"math" "math"
"strings" "strings"
@ -269,6 +270,12 @@ func CreatePostStar(postID, userID int64) (*model.PostStar, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
// 私密post不可操作
if post.Visibility == model.PostVisitPrivate {
return nil, errors.New("no permision")
}
star, err := ds.CreatePostStar(postID, userID) star, err := ds.CreatePostStar(postID, userID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -294,6 +301,12 @@ func DeletePostStar(star *model.PostStar) error {
if err != nil { if err != nil {
return err return err
} }
// 私密post不可操作
if post.Visibility == model.PostVisitPrivate {
return errors.New("no permision")
}
// 更新Post点赞数 // 更新Post点赞数
post.UpvoteCount-- post.UpvoteCount--
ds.UpdatePost(post) ds.UpdatePost(post)
@ -314,6 +327,12 @@ func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
// 私密post不可操作
if post.Visibility == model.PostVisitPrivate {
return nil, errors.New("no permision")
}
collection, err := ds.CreatePostCollection(postID, userID) collection, err := ds.CreatePostCollection(postID, userID)
if err != nil { if err != nil {
return nil, err return nil, err
@ -339,6 +358,12 @@ func DeletePostCollection(collection *model.PostCollection) error {
if err != nil { if err != nil {
return err return err
} }
// 私密post不可操作
if post.Visibility == model.PostVisitPrivate {
return errors.New("no permision")
}
// 更新Post点赞数 // 更新Post点赞数
post.CollectionCount-- post.CollectionCount--
ds.UpdatePost(post) ds.UpdatePost(post)

@ -274,21 +274,11 @@ func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated,
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
postIDs := []int64{} var posts []*model.Post
for _, collection := range collections { for _, collection := range collections {
postIDs = append(postIDs, collection.PostID) posts = append(posts, collection.Post)
} }
postsFormated, err := ds.MergePosts(posts)
// 获取Posts
posts, err := ds.GetPosts(&model.ConditionsT{
"id IN ?": postIDs,
"ORDER": "id DESC",
}, 0, 0)
if err != nil {
return nil, 0, err
}
postsFormated, err := FormatPosts(posts)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
@ -306,21 +296,12 @@ func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
postIDs := []int64{}
for _, star := range stars {
postIDs = append(postIDs, star.PostID)
}
// 获取Posts var posts []*model.Post
posts, err := ds.GetPosts(&model.ConditionsT{ for _, star := range stars {
"id IN ?": postIDs, posts = append(posts, star.Post)
"ORDER": "id DESC",
}, 0, 0)
if err != nil {
return nil, 0, err
} }
postsFormated, err := ds.MergePosts(posts)
postsFormated, err := FormatPosts(posts)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }

Loading…
Cancel
Save