84 lines
2.4 KiB
Go
84 lines
2.4 KiB
Go
package dal
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.guxuan/haibei/internal/mods/common/schema"
|
|
"github.guxuan/haibei/pkg/errors"
|
|
"github.guxuan/haibei/pkg/util"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// Get notice storage instance
|
|
func GetNoticeDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
|
|
return util.GetDB(ctx, defDB).Model(new(schema.Notice))
|
|
}
|
|
|
|
// Defining the `Notice` data access object.
|
|
type Notice struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
// Query notices from the database based on the provided parameters and options.
|
|
func (a *Notice) Query(ctx context.Context, params schema.NoticeQueryParam, opts ...schema.NoticeQueryOptions) (*schema.NoticeQueryResult, error) {
|
|
var opt schema.NoticeQueryOptions
|
|
if len(opts) > 0 {
|
|
opt = opts[0]
|
|
}
|
|
|
|
db := GetNoticeDB(ctx, a.DB)
|
|
|
|
var list schema.Notices
|
|
pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
queryResult := &schema.NoticeQueryResult{
|
|
PageResult: pageResult,
|
|
Data: list,
|
|
}
|
|
return queryResult, nil
|
|
}
|
|
|
|
// Get the specified notice from the database.
|
|
func (a *Notice) Get(ctx context.Context, id uint, opts ...schema.NoticeQueryOptions) (*schema.Notice, error) {
|
|
var opt schema.NoticeQueryOptions
|
|
if len(opts) > 0 {
|
|
opt = opts[0]
|
|
}
|
|
|
|
item := new(schema.Notice)
|
|
ok, err := util.FindOne(ctx, GetNoticeDB(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
|
|
}
|
|
|
|
// Exists checks if the specified notice exists in the database.
|
|
func (a *Notice) Exists(ctx context.Context, id uint) (bool, error) {
|
|
ok, err := util.Exists(ctx, GetNoticeDB(ctx, a.DB).Where("id=?", id))
|
|
return ok, errors.WithStack(err)
|
|
}
|
|
|
|
// Create a new notice.
|
|
func (a *Notice) Create(ctx context.Context, item *schema.Notice) error {
|
|
result := GetNoticeDB(ctx, a.DB).Create(item)
|
|
return errors.WithStack(result.Error)
|
|
}
|
|
|
|
// Update the specified notice in the database.
|
|
func (a *Notice) Update(ctx context.Context, item *schema.Notice) error {
|
|
result := GetNoticeDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
|
|
return errors.WithStack(result.Error)
|
|
}
|
|
|
|
// Delete the specified notice from the database.
|
|
func (a *Notice) Delete(ctx context.Context, id uint) error {
|
|
result := GetNoticeDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Notice))
|
|
return errors.WithStack(result.Error)
|
|
}
|