55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
package ldmod
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// singletonID : l'unique ligne de ld_mod (voir la contrainte CHECK (id = 1)
|
|
// de la migration 000035).
|
|
const singletonID int16 = 1
|
|
|
|
var ErrNotFound = errors.New("ld mod settings not found")
|
|
|
|
type Repository interface {
|
|
Get(ctx context.Context) (*LDMod, error)
|
|
Update(ctx context.Context, m *LDMod) (*LDMod, error)
|
|
}
|
|
|
|
type gormRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewRepository(db *gorm.DB) Repository {
|
|
return &gormRepository{db: db}
|
|
}
|
|
|
|
func (r *gormRepository) Get(ctx context.Context) (*LDMod, error) {
|
|
var m LDMod
|
|
err := r.db.WithContext(ctx).First(&m, singletonID).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, ErrNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &m, nil
|
|
}
|
|
|
|
// Update écrit tous les réglages sur la ligne unique. Select("*") est voulu :
|
|
// sans lui GORM ignore les champs à valeur zéro d'une struct, donc passer
|
|
// false n'écrirait rien et l'admin ne pourrait jamais désactiver le toggle.
|
|
func (r *gormRepository) Update(ctx context.Context, m *LDMod) (*LDMod, error) {
|
|
m.ID = singletonID
|
|
res := r.db.WithContext(ctx).Model(&LDMod{}).Where("id = ?", singletonID).Select("*").Updates(m)
|
|
if res.Error != nil {
|
|
return nil, res.Error
|
|
}
|
|
if res.RowsAffected == 0 {
|
|
return nil, ErrNotFound
|
|
}
|
|
return r.Get(ctx)
|
|
}
|