This commit is contained in:
2025-04-07 11:21:43 +08:00
parent 51a888e470
commit f100427f8b
11 changed files with 350 additions and 26 deletions

View File

@@ -0,0 +1,69 @@
package store
import (
"context"
"sync"
"management/internal/erpserver/store/system"
"gorm.io/gorm"
)
var (
once sync.Once
// 全局变量,方便其它包直接调用已初始化好的 datastore 实例.
engine *datastore
)
// IStore 定义了 Store 层需要实现的方法.
type IStore interface {
DB(ctx context.Context) *gorm.DB
TX(ctx context.Context, fn func(ctx context.Context) error) error
User() system.UserStore
}
// transactionKey 用于在 context.Context 中存储事务上下文的键.
type transactionKey struct{}
// datastore 是 IStore 的具体实现.
type datastore struct {
core *gorm.DB
}
// 确保 datastore 实现了 IStore 接口.
var _ IStore = (*datastore)(nil)
// NewStore 创建一个 IStore 类型的实例.
func NewStore(db *gorm.DB) *datastore {
// 确保 engine 只被初始化一次
once.Do(func() {
engine = &datastore{db}
})
return engine
}
func (store *datastore) DB(ctx context.Context) *gorm.DB {
db := store.core
// 从上下文中提取事务实例
if tx, ok := ctx.Value(transactionKey{}).(*gorm.DB); ok {
db = tx
}
return db
}
func (store *datastore) TX(ctx context.Context, fn func(ctx context.Context) error) error {
return store.core.WithContext(ctx).Transaction(
func(tx *gorm.DB) error {
ctx = context.WithValue(ctx, transactionKey{}, tx)
return fn(ctx)
},
)
}
// Users 返回一个实现了 UserStore 接口的实例.
func (store *datastore) User() system.UserStore {
return system.NewUserStore(store.core)
}

View File

@@ -0,0 +1,63 @@
package system
import (
"context"
"management/internal/erpserver/model/system"
"gorm.io/gorm"
)
// UserStore 定义了 user 模块在 store 层所实现的方法.
type UserStore interface {
Create(ctx context.Context, obj *system.User) error
Update(ctx context.Context, obj *system.User) error
Get(ctx context.Context, id int32) (*system.User, error)
GetByEmail(ctx context.Context, email string) (*system.User, error)
UserExpansion
}
// UserExpansion 定义了用户操作的附加方法.
type UserExpansion interface{}
// userStore 是 UserStore 接口的实现.
type userStore struct {
db *gorm.DB
}
// 确保 userStore 实现了 UserStore 接口.
var _ UserStore = (*userStore)(nil)
// NewUserStore 创建 userStore 的实例.
func NewUserStore(db *gorm.DB) *userStore {
return &userStore{
db: db,
}
}
func (s *userStore) Create(ctx context.Context, obj *system.User) error {
return s.db.WithContext(ctx).Create(obj).Error
}
func (s *userStore) Update(ctx context.Context, obj *system.User) error {
return s.db.WithContext(ctx).Save(obj).Error
}
func (s *userStore) Get(ctx context.Context, id int32) (*system.User, error) {
var user system.User
err := s.db.WithContext(ctx).Where("id = ?", id).First(&user).Error
if err != nil {
return nil, err
}
return &user, nil
}
func (s *userStore) GetByEmail(ctx context.Context, email string) (*system.User, error) {
var user system.User
err := s.db.WithContext(ctx).Where("email = ?", email).First(&user).Error
if err != nil {
return nil, err
}
return &user, nil
}