1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/services/alias.go
Ferdinand Mütsch 3c2dc78c93 refactor: refactor migrations and add fixtures
feat: introduce key-value store
feat: imprint page (resolve #23)
chore: remove default user
chore: remove packr
2020-05-30 20:41:27 +02:00

55 lines
1.1 KiB
Go

package services
import (
"errors"
"sync"
"github.com/jinzhu/gorm"
"github.com/muety/wakapi/models"
)
type AliasService struct {
Config *models.Config
Db *gorm.DB
}
func NewAliasService(db *gorm.DB) *AliasService {
return &AliasService{
Config: models.GetConfig(),
Db: db,
}
}
var userAliases sync.Map
func (srv *AliasService) LoadUserAliases(userId string) error {
var aliases []*models.Alias
if err := srv.Db.
Where(&models.Alias{UserID: userId}).
Find(&aliases).Error; err != nil {
return err
}
userAliases.Store(userId, aliases)
return nil
}
func (srv *AliasService) GetAliasOrDefault(userId string, summaryType uint8, value string) (string, error) {
if ua, ok := userAliases.Load(userId); ok {
for _, a := range ua.([]*models.Alias) {
if a.Type == summaryType && a.Value == value {
return a.Key, nil
}
}
return value, nil
}
return "", errors.New("user aliases not initialized")
}
func (srv *AliasService) IsInitialized(userId string) bool {
if _, ok := userAliases.Load(userId); ok {
return true
}
return false
}