Files
backend/internal/repository/sensitive_word_repo.go

67 lines
2.0 KiB
Go
Raw Normal View History

package repository
import (
"context"
"with_you/internal/model"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type SensitiveWordRepository interface {
Create(ctx context.Context, word *model.SensitiveWord) error
GetByWord(ctx context.Context, word string) (*model.SensitiveWord, error)
Update(ctx context.Context, word *model.SensitiveWord) error
Upsert(ctx context.Context, word *model.SensitiveWord) error
DeactivateByWord(ctx context.Context, word string) error
ListActive(ctx context.Context) ([]model.SensitiveWord, error)
}
type sensitiveWordRepository struct {
db *gorm.DB
}
func NewSensitiveWordRepository(db *gorm.DB) SensitiveWordRepository {
return &sensitiveWordRepository{db: db}
}
func (r *sensitiveWordRepository) Create(ctx context.Context, word *model.SensitiveWord) error {
return r.db.WithContext(ctx).Create(word).Error
}
func (r *sensitiveWordRepository) GetByWord(ctx context.Context, word string) (*model.SensitiveWord, error) {
var sw model.SensitiveWord
err := r.db.WithContext(ctx).Where("word = ?", word).First(&sw).Error
if err != nil {
return nil, err
}
return &sw, nil
}
func (r *sensitiveWordRepository) Update(ctx context.Context, word *model.SensitiveWord) error {
return r.db.WithContext(ctx).Save(word).Error
}
func (r *sensitiveWordRepository) Upsert(ctx context.Context, word *model.SensitiveWord) error {
return r.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "word"}},
DoUpdates: clause.AssignmentColumns([]string{
"category", "level", "is_active", "updated_by", "remark", "updated_at",
}),
}).Create(word).Error
}
func (r *sensitiveWordRepository) DeactivateByWord(ctx context.Context, word string) error {
return r.db.WithContext(ctx).
Model(&model.SensitiveWord{}).
Where("word = ?", word).
Update("is_active", false).Error
}
func (r *sensitiveWordRepository) ListActive(ctx context.Context) ([]model.SensitiveWord, error) {
var words []model.SensitiveWord
err := r.db.WithContext(ctx).Where("is_active = ?", true).Find(&words).Error
return words, err
}