Files
backend/internal/repository/transaction.go
lan cf36b1350d refactor: introduce Wire dependency injection and interface-based architecture
- Add Google Wire for compile-time dependency injection
- Replace concrete service types with interfaces across handlers
- Remove global state (DB, cache) in favor of constructor injection
- Split monolithic files into focused modules:
  - config: separate files for each config domain
  - dto: converters split by domain (user, post, message, group)
  - cache: separate metrics.go and redis_cache.go
- Introduce unified apperrors package with string-based error codes
- Add transaction support with context-aware repository methods
- Upgrade golang.org/x/crypto from 0.17.0 to 0.26.0
2026-03-13 09:38:18 +08:00

44 lines
1.1 KiB
Go

package repository
import (
"context"
"gorm.io/gorm"
)
// TransactionManager 事务管理器接口
type TransactionManager interface {
// RunInTransaction 在事务中执行函数
RunInTransaction(ctx context.Context, fn func(ctx context.Context) error) error
}
// gormTransactionManager GORM 事务管理器实现
type gormTransactionManager struct {
db *gorm.DB
}
// NewTransactionManager 创建事务管理器
func NewTransactionManager(db *gorm.DB) TransactionManager {
return &gormTransactionManager{db: db}
}
// RunInTransaction 在事务中执行函数
func (m *gormTransactionManager) RunInTransaction(ctx context.Context, fn func(ctx context.Context) error) error {
return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// 将事务 TX 存入 context
ctxWithTx := context.WithValue(ctx, txKey{}, tx)
return fn(ctxWithTx)
})
}
// txKey 事务 context key
type txKey struct{}
// GetTxFromContext 从 context 获取事务 TX
func GetTxFromContext(ctx context.Context) *gorm.DB {
if tx, ok := ctx.Value(txKey{}).(*gorm.DB); ok {
return tx
}
return nil
}