package Database
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
|
|
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/clause"
|
|
)
|
|
|
|
func GetPosts(page, pageSize int, search string) ([]Models.Post, error) {
|
|
var (
|
|
posts []Models.Post
|
|
query *gorm.DB
|
|
offset int
|
|
err error
|
|
)
|
|
|
|
switch {
|
|
case pageSize > 100:
|
|
pageSize = 100
|
|
case pageSize <= 0:
|
|
pageSize = 10
|
|
}
|
|
|
|
offset = page * pageSize
|
|
|
|
search = fmt.Sprintf("%%%s%%", search)
|
|
|
|
query = DB.Model(Models.Post{}).
|
|
Preload(clause.Associations).
|
|
Offset(offset).
|
|
Limit(pageSize).
|
|
Order("created_at desc")
|
|
|
|
if search != "%%" {
|
|
query = query.
|
|
Where("title LIKE ?", search).
|
|
Or("content LIKE ?", search)
|
|
}
|
|
|
|
err = query.
|
|
Find(&posts).
|
|
Error
|
|
|
|
return posts, err
|
|
}
|
|
|
|
func GetFrontPagePosts() ([]Models.Post, error) {
|
|
var (
|
|
posts []Models.Post
|
|
err error
|
|
)
|
|
|
|
err = DB.Where("front_page = ?", true).
|
|
Order("order asc").
|
|
Find(&posts).
|
|
Error
|
|
|
|
return posts, err
|
|
}
|
|
|
|
func GetPostById(id string) (Models.Post, error) {
|
|
var (
|
|
postData Models.Post
|
|
err error
|
|
)
|
|
|
|
err = DB.Preload(clause.Associations).
|
|
First(&postData, "id = ?", id).
|
|
Error
|
|
|
|
return postData, err
|
|
}
|
|
|
|
func CreatePost(postData *Models.Post) error {
|
|
return DB.Session(&gorm.Session{FullSaveAssociations: true}).
|
|
Create(postData).
|
|
Error
|
|
}
|
|
|
|
func UpdatePost(id string, postData *Models.Post) (Models.Post, error) {
|
|
var (
|
|
err error
|
|
)
|
|
|
|
DB.Model(postData).
|
|
Where("id = ?", id).
|
|
Association("PostLinks").
|
|
Replace(postData.PostLinks)
|
|
|
|
err = DB.Model(&Models.Post{}).
|
|
Select("*").
|
|
Omit("id", "created_at", "updated_at", "deleted_at").
|
|
Where("id = ?", id).
|
|
Updates(postData).
|
|
Error
|
|
|
|
if err != nil {
|
|
return Models.Post{}, err
|
|
}
|
|
|
|
return GetPostById(id)
|
|
}
|
|
|
|
func DeletePost(postData *Models.Post) error {
|
|
return DB.Session(&gorm.Session{FullSaveAssociations: true}).
|
|
Delete(postData).
|
|
Error
|
|
}
|