84 lines
2.3 KiB
Go
84 lines
2.3 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 GetProductDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
|
|
return util.GetDB(ctx, defDB).Model(new(schema.Product))
|
|
}
|
|
|
|
type Product struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
func (a *Product) Query(ctx context.Context, params schema.ProductQueryParam, opts ...schema.ProductQueryOptions) (*schema.ProductQueryResult, error) {
|
|
var opt schema.ProductQueryOptions
|
|
if len(opts) > 0 {
|
|
opt = opts[0]
|
|
}
|
|
|
|
db := GetProductDB(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.CategoryID; v > 0 {
|
|
db = db.Where("categoryId = ?", v)
|
|
}
|
|
var list schema.Products
|
|
pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
queryResult := &schema.ProductQueryResult{
|
|
PageResult: pageResult,
|
|
Data: list,
|
|
}
|
|
return queryResult, nil
|
|
}
|
|
|
|
func (a *Product) Get(ctx context.Context, id string, opts ...schema.ProductQueryOptions) (*schema.Product, error) {
|
|
var opt schema.ProductQueryOptions
|
|
if len(opts) > 0 {
|
|
opt = opts[0]
|
|
}
|
|
|
|
item := new(schema.Product)
|
|
ok, err := util.FindOne(ctx, GetProductDB(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
|
|
}
|
|
|
|
func (a *Product) Exists(ctx context.Context, id string) (bool, error) {
|
|
ok, err := util.Exists(ctx, GetProductDB(ctx, a.DB).Where("id=?", id))
|
|
return ok, errors.WithStack(err)
|
|
}
|
|
|
|
func (a *Product) Create(ctx context.Context, item *schema.Product) error {
|
|
result := GetProductDB(ctx, a.DB).Create(item)
|
|
return errors.WithStack(result.Error)
|
|
}
|
|
|
|
func (a *Product) Update(ctx context.Context, item *schema.Product) error {
|
|
result := GetProductDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
|
|
return errors.WithStack(result.Error)
|
|
}
|
|
|
|
func (a *Product) Delete(ctx context.Context, id string) error {
|
|
result := GetProductDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Product))
|
|
return errors.WithStack(result.Error)
|
|
}
|