Files
gochat/internal/repository/repository.go
T
2026-06-04 15:44:48 +08:00

65 lines
1.8 KiB
Go

package repository
import (
"context"
"gorm.io/gorm"
)
// BaseRepository provides generic CRUD operations for any GORM model.
type BaseRepository[T any] struct {
db *gorm.DB
}
// NewBaseRepository creates a new BaseRepository for the given model type.
func NewBaseRepository[T any](db *gorm.DB) *BaseRepository[T] {
return &BaseRepository[T]{db: db}
}
// Create inserts a new record.
func (r *BaseRepository[T]) Create(ctx context.Context, entity *T) error {
return r.db.WithContext(ctx).Create(entity).Error
}
// GetByID fetches a single record by primary key.
func (r *BaseRepository[T]) GetByID(ctx context.Context, id uint) (*T, error) {
var entity T
if err := r.db.WithContext(ctx).First(&entity, id).Error; err != nil {
return nil, err
}
return &entity, nil
}
// Update modifies an existing record.
func (r *BaseRepository[T]) Update(ctx context.Context, entity *T) error {
return r.db.WithContext(ctx).Save(entity).Error
}
// Delete soft-deletes a record (if model supports soft delete) or hard-deletes.
func (r *BaseRepository[T]) Delete(ctx context.Context, id uint) error {
var entity T
return r.db.WithContext(ctx).Delete(&entity, id).Error
}
// List returns all records with optional pagination.
func (r *BaseRepository[T]) List(ctx context.Context, offset, limit int) ([]T, error) {
var entities []T
if err := r.db.WithContext(ctx).Offset(offset).Limit(limit).Find(&entities).Error; err != nil {
return nil, err
}
return entities, nil
}
// Count returns total number of records.
func (r *BaseRepository[T]) Count(ctx context.Context) (int64, error) {
var count int64
if err := r.db.WithContext(ctx).Model(new(T)).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
// DB returns the underlying gorm.DB for complex queries.
func (r *BaseRepository[T]) DB() *gorm.DB {
return r.db
}