90 lines
2.6 KiB
Go
90 lines
2.6 KiB
Go
package dal
|
|
|
|
import (
|
|
"context"
|
|
"github.com/guxuan/hailin_service/internal/mods/rbac/schema"
|
|
"github.com/guxuan/hailin_service/pkg/errors"
|
|
"github.com/guxuan/hailin_service/pkg/util"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func GetArticleDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
|
|
return util.GetDB(ctx, defDB).Model(new(schema.Article))
|
|
}
|
|
|
|
type Article struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
// Query roles from the database based on the provided parameters and options.
|
|
func (a *Article) Query(ctx context.Context, params schema.ArticleQueryParam, opts ...schema.ArticleQueryOptions) (*schema.ArticleQueryResult, error) {
|
|
var opt schema.ArticleQueryOptions
|
|
if len(opts) > 0 {
|
|
opt = opts[0]
|
|
}
|
|
|
|
db := GetArticleDB(ctx, a.DB)
|
|
|
|
if v := params.LikeTitle; len(v) > 0 {
|
|
db = db.Where("title LIKE ?", "%"+v+"%")
|
|
}
|
|
if v := params.Status; len(v) > 0 {
|
|
db = db.Where("status = ?", v)
|
|
}
|
|
if v := params.Typer; len(v) > 0 {
|
|
db = db.Where("type = ?", v)
|
|
}
|
|
var list schema.Articles
|
|
pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
queryResult := &schema.ArticleQueryResult{
|
|
PageResult: pageResult,
|
|
Data: list,
|
|
}
|
|
return queryResult, nil
|
|
}
|
|
|
|
// Get the specified role from the database.
|
|
func (a *Article) Get(ctx context.Context, id string, opts ...schema.ArticleQueryOptions) (*schema.Article, error) {
|
|
var opt schema.ArticleQueryOptions
|
|
if len(opts) > 0 {
|
|
opt = opts[0]
|
|
}
|
|
|
|
item := new(schema.Article)
|
|
ok, err := util.FindOne(ctx, GetArticleDB(ctx, a.DB).Where("id=?", id), opt.QueryOptions, item)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
} else if !ok {
|
|
return nil, nil
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
// Exist checks if the specified role exists in the database.
|
|
func (a *Article) Exists(ctx context.Context, id string) (bool, error) {
|
|
ok, err := util.Exists(ctx, GetArticleDB(ctx, a.DB).Where("id=?", id))
|
|
return ok, errors.WithStack(err)
|
|
}
|
|
|
|
// Create a new role.
|
|
func (a *Article) Create(ctx context.Context, item *schema.Article) error {
|
|
result := GetArticleDB(ctx, a.DB).Create(item)
|
|
return errors.WithStack(result.Error)
|
|
}
|
|
|
|
// Update the specified role in the database.
|
|
func (a *Article) Update(ctx context.Context, item *schema.Article) error {
|
|
result := GetArticleDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
|
|
return errors.WithStack(result.Error)
|
|
}
|
|
|
|
// Delete the specified role from the database.
|
|
func (a *Article) Delete(ctx context.Context, id string) error {
|
|
result := GetArticleDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Article))
|
|
return errors.WithStack(result.Error)
|
|
}
|