2020-11-01 18:56:36 +03:00
|
|
|
package repositories
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"github.com/muety/wakapi/models"
|
2020-11-01 22:14:10 +03:00
|
|
|
"gorm.io/gorm"
|
2021-01-17 11:24:09 +03:00
|
|
|
"gorm.io/gorm/clause"
|
2020-11-01 18:56:36 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type KeyValueRepository struct {
|
|
|
|
db *gorm.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewKeyValueRepository(db *gorm.DB) *KeyValueRepository {
|
|
|
|
return &KeyValueRepository{db: db}
|
|
|
|
}
|
|
|
|
|
2021-04-18 11:59:13 +03:00
|
|
|
func (r *KeyValueRepository) GetAll() ([]*models.KeyStringValue, error) {
|
|
|
|
var keyValues []*models.KeyStringValue
|
|
|
|
if err := r.db.Find(&keyValues).Error; err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return keyValues, nil
|
|
|
|
}
|
|
|
|
|
2020-11-01 18:56:36 +03:00
|
|
|
func (r *KeyValueRepository) GetString(key string) (*models.KeyStringValue, error) {
|
|
|
|
kv := &models.KeyStringValue{}
|
|
|
|
if err := r.db.
|
|
|
|
Where(&models.KeyStringValue{Key: key}).
|
|
|
|
First(&kv).Error; err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return kv, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *KeyValueRepository) PutString(kv *models.KeyStringValue) error {
|
|
|
|
result := r.db.
|
2021-01-17 11:24:09 +03:00
|
|
|
Clauses(clause.OnConflict{
|
|
|
|
UpdateAll: true,
|
|
|
|
}).
|
2020-11-01 18:56:36 +03:00
|
|
|
Where(&models.KeyStringValue{Key: kv.Key}).
|
|
|
|
Assign(kv).
|
2021-01-17 11:24:09 +03:00
|
|
|
Create(kv)
|
2020-11-01 18:56:36 +03:00
|
|
|
|
|
|
|
if err := result.Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *KeyValueRepository) DeleteString(key string) error {
|
|
|
|
result := r.db.
|
|
|
|
Delete(&models.KeyStringValue{}, &models.KeyStringValue{Key: key})
|
|
|
|
|
|
|
|
if err := result.Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if result.RowsAffected != 1 {
|
|
|
|
return errors.New("nothing deleted")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|