package checkoutfields import ( "context" "errors" "gorm.io/gorm" ) // singletonID : l'unique ligne de checkout_fields (voir la contrainte // CHECK (id = 1) de la migration 000032). const singletonID int16 = 1 var ErrNotFound = errors.New("checkout fields not found") type Repository interface { Get(ctx context.Context) (*CheckoutField, error) Update(ctx context.Context, f *CheckoutField) (*CheckoutField, error) } type gormRepository struct { db *gorm.DB } func NewRepository(db *gorm.DB) Repository { return &gormRepository{db: db} } func (r *gormRepository) Get(ctx context.Context) (*CheckoutField, error) { var f CheckoutField err := r.db.WithContext(ctx).First(&f, singletonID).Error if errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrNotFound } if err != nil { return nil, err } return &f, 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 un champ. func (r *gormRepository) Update(ctx context.Context, f *CheckoutField) (*CheckoutField, error) { f.ID = singletonID res := r.db.WithContext(ctx).Model(&CheckoutField{}).Where("id = ?", singletonID).Select("*").Updates(f) if res.Error != nil { return nil, res.Error } if res.RowsAffected == 0 { return nil, ErrNotFound } return r.Get(ctx) }