2020-05-30 21:41:27 +03:00
|
|
|
package services
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"github.com/jinzhu/gorm"
|
2020-09-29 19:55:07 +03:00
|
|
|
"github.com/muety/wakapi/config"
|
2020-05-30 21:41:27 +03:00
|
|
|
"github.com/muety/wakapi/models"
|
|
|
|
)
|
|
|
|
|
|
|
|
type KeyValueService struct {
|
2020-09-29 19:55:07 +03:00
|
|
|
Config *config.Config
|
2020-05-30 21:41:27 +03:00
|
|
|
Db *gorm.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewKeyValueService(db *gorm.DB) *KeyValueService {
|
|
|
|
return &KeyValueService{
|
2020-09-29 19:55:07 +03:00
|
|
|
Config: config.Get(),
|
2020-05-30 21:41:27 +03:00
|
|
|
Db: db,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *KeyValueService) GetString(key string) (*models.KeyStringValue, error) {
|
|
|
|
kv := &models.KeyStringValue{}
|
|
|
|
if err := srv.Db.
|
|
|
|
Where(&models.KeyStringValue{Key: key}).
|
|
|
|
First(&kv).Error; err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return kv, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *KeyValueService) PutString(kv *models.KeyStringValue) error {
|
|
|
|
result := srv.Db.
|
|
|
|
Where(&models.KeyStringValue{Key: kv.Key}).
|
|
|
|
Assign(kv).
|
|
|
|
FirstOrCreate(kv)
|
|
|
|
|
|
|
|
if err := result.Error; err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if result.RowsAffected != 1 {
|
|
|
|
return errors.New("nothing updated")
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *KeyValueService) DeleteString(key string) error {
|
|
|
|
result := srv.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
|
|
|
|
}
|