66db64267c
- 新增 core.BaseRepo 泛型仓库,提供增删改查基本操作方法 - 实现 Insert、SelectById、List、Update 和 Delete 方法,支持上下文传递 - 新增 ChannelRepo、ModelRepo 和 APIKeyRepo,均基于 BaseRepo 实现 - 规范化仓库结构,提升代码复用性和维护性 - 支持对不同模型的统一数据访问接口设计
49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package core
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// BaseRepository 是一个泛型接口,定义了基本的增删改查操作
|
|
type BaseRepository[T any] interface {
|
|
// Insert 插入一条记录
|
|
Insert(ctx context.Context, record *T) error
|
|
// SelectById 根据id查询一条记录
|
|
SelectById(ctx context.Context, id int64) (*T, error)
|
|
// List 查询所有记录
|
|
List(ctx context.Context) ([]*T, error)
|
|
// Update 更新一条记录
|
|
Update(ctx context.Context, record *T) error
|
|
// Delete 根据id删除一条记录
|
|
Delete(ctx context.Context, id int64) error
|
|
}
|
|
|
|
type BaseRepo[T any] struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func (repo *BaseRepo[T]) Insert(ctx context.Context, record *T) error {
|
|
return repo.db.WithContext(ctx).Create(record).Error
|
|
}
|
|
|
|
func (repo *BaseRepo[T]) SelectById(ctx context.Context, id int64) (*T, error) {
|
|
var result T
|
|
return &result, repo.db.WithContext(ctx).First(&result, id).Error
|
|
}
|
|
|
|
func (repo *BaseRepo[T]) List(ctx context.Context) ([]*T, error) {
|
|
var results []*T
|
|
return results, repo.db.WithContext(ctx).Find(&results).Error
|
|
}
|
|
|
|
func (repo *BaseRepo[T]) Update(ctx context.Context, record *T) error {
|
|
return repo.db.WithContext(ctx).Save(record).Error
|
|
}
|
|
|
|
func (repo *BaseRepo[T]) Delete(ctx context.Context, id int64) error {
|
|
var model T
|
|
return repo.db.WithContext(ctx).Delete(&model, id).Error
|
|
}
|