72 lines
2.0 KiB
Go
72 lines
2.0 KiB
Go
package model
|
|
|
|
import (
|
|
"time"
|
|
)
|
|
|
|
type Document struct {
|
|
Id int `json:"id" gorm:"primaryKey"`
|
|
Title string `json:"title" gorm:"not null"`
|
|
Slug string `json:"slug" gorm:"uniqueIndex;not null"`
|
|
Content string `json:"content" gorm:"type:text;not null"`
|
|
CategoryId *int `json:"category_id" gorm:"index"`
|
|
Visibility string `json:"visibility" gorm:"default:'public'"` // public, auth, admin
|
|
SortOrder int `json:"sort_order" gorm:"default:0"`
|
|
AuthorId int `json:"author_id" gorm:"not null"`
|
|
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
|
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
|
}
|
|
|
|
func GetDocuments(keyword string, visibility string, categoryId *int, startIdx int, num int) ([]*Document, int64, error) {
|
|
query := DB.Model(&Document{})
|
|
if keyword != "" {
|
|
like := "%" + keyword + "%"
|
|
query = query.Where("title LIKE ? OR content LIKE ?", like, like)
|
|
}
|
|
if visibility != "" {
|
|
query = query.Where("visibility = ?", visibility)
|
|
}
|
|
if categoryId != nil {
|
|
query = query.Where("category_id = ?", *categoryId)
|
|
}
|
|
var total int64
|
|
if err := query.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
var documents []*Document
|
|
if err := query.Order("sort_order ASC, id DESC").Offset(startIdx).Limit(num).Find(&documents).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
return documents, total, nil
|
|
}
|
|
|
|
func GetDocumentBySlug(slug string) (*Document, error) {
|
|
var doc Document
|
|
err := DB.Where("slug = ?", slug).First(&doc).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &doc, nil
|
|
}
|
|
|
|
func GetDocumentById(id int) (*Document, error) {
|
|
var doc Document
|
|
err := DB.First(&doc, id).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &doc, nil
|
|
}
|
|
|
|
func CreateDocument(doc *Document) error {
|
|
return DB.Create(doc).Error
|
|
}
|
|
|
|
func UpdateDocument(doc *Document) error {
|
|
return DB.Model(doc).Select("title", "slug", "content", "category_id", "visibility", "sort_order").Updates(doc).Error
|
|
}
|
|
|
|
func DeleteDocument(id int) error {
|
|
return DB.Delete(&Document{}, id).Error
|
|
}
|