jinshan/internal/mods/app/dal/app.dal.go
2025-06-19 10:35:26 +08:00

84 lines
2.3 KiB
Go

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