2025-06-19 10:35:26 +08:00

84 lines
2.4 KiB
Go

package dal
import (
"context"
"gitlab.guxuan.icu/jinshan_community/internal/mods/product/schema"
"gitlab.guxuan.icu/jinshan_community/pkg/errors"
"gitlab.guxuan.icu/jinshan_community/pkg/util"
"gorm.io/gorm"
)
// Get order storage instance
func GetOrderDB(ctx context.Context, defDB *gorm.DB) *gorm.DB {
return util.GetDB(ctx, defDB).Model(new(schema.Order))
}
// Defining the `Order` data access object.
type Order struct {
DB *gorm.DB
}
// Query orders from the database based on the provided parameters and options.
func (a *Order) Query(ctx context.Context, params schema.OrderQueryParam, opts ...schema.OrderQueryOptions) (*schema.OrderQueryResult, error) {
var opt schema.OrderQueryOptions
if len(opts) > 0 {
opt = opts[0]
}
db := GetOrderDB(ctx, a.DB)
var list schema.Orders
pageResult, err := util.WrapPageQuery(ctx, db, params.PaginationParam, opt.QueryOptions, &list)
if err != nil {
return nil, errors.WithStack(err)
}
queryResult := &schema.OrderQueryResult{
PageResult: pageResult,
Data: list,
}
return queryResult, nil
}
// Get the specified order from the database.
func (a *Order) Get(ctx context.Context, id string, opts ...schema.OrderQueryOptions) (*schema.Order, error) {
var opt schema.OrderQueryOptions
if len(opts) > 0 {
opt = opts[0]
}
item := new(schema.Order)
ok, err := util.FindOne(ctx, GetOrderDB(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 order exists in the database.
func (a *Order) Exists(ctx context.Context, id string) (bool, error) {
ok, err := util.Exists(ctx, GetOrderDB(ctx, a.DB).Where("id=?", id))
return ok, errors.WithStack(err)
}
// Create a new order.
func (a *Order) Create(ctx context.Context, item *schema.Order) error {
result := GetOrderDB(ctx, a.DB).Create(item)
return errors.WithStack(result.Error)
}
// Update the specified order in the database.
func (a *Order) Update(ctx context.Context, item *schema.Order) error {
result := GetOrderDB(ctx, a.DB).Where("id=?", item.ID).Select("*").Omit("created_at").Updates(item)
return errors.WithStack(result.Error)
}
// Delete the specified order from the database.
func (a *Order) Delete(ctx context.Context, id string) error {
result := GetOrderDB(ctx, a.DB).Where("id=?", id).Delete(new(schema.Order))
return errors.WithStack(result.Error)
}