-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpost.go
55 lines (42 loc) · 1.5 KB
/
post.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright 2023 daz-3ux(杨鹏达) <[email protected]>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://github.com/Daz-3ux/dBlog.
package model
import (
"sync/atomic"
"time"
"gorm.io/gorm"
"github.com/Daz-3ux/dBlog/pkg/util/id"
)
type PostM struct {
ID int64 `gorm:"column:id;primary_key"` // unique id for the post, server as the primary key
Username string `gorm:"column:username"` // author of the post
PostID string `gorm:"column:postID"` // unique id for the post, used as a user-friendly ID
Title string `gorm:"column:title"` // title of the post
Content string `gorm:"column:content"` // content of the post
CreatedAt time.Time `gorm:"column:createdAt"` // time when the post was created
UpdatedAt time.Time `gorm:"column:updatedAt"` // time when the post was updated
}
// TableName sets the insert table name for this struct type
func (p *PostM) TableName() string {
return "posts"
}
func (p *PostM) BeforeCreate(tx *gorm.DB) error {
p.PostID = "post-" + id.GenShortID()
return nil
}
func (p *PostM) AfterCreate(tx *gorm.DB) error {
if tx.Error != nil {
return tx.Error
}
var user UserM
if err := tx.Where("username = ?", p.Username).First(&user).Error; err != nil {
return err
}
atomic.AddInt64(&user.PostCount, 1)
if err := tx.Save(&user).Error; err != nil {
return err
}
return nil
}