1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/services/alias.go

50 lines
995 B
Go
Raw Normal View History

2019-07-06 18:53:20 +03:00
package services
import (
"errors"
2019-10-10 17:47:19 +03:00
"sync"
2019-07-06 18:53:20 +03:00
"github.com/jinzhu/gorm"
2020-03-31 13:22:17 +03:00
"github.com/muety/wakapi/models"
2019-07-06 18:53:20 +03:00
)
type AliasService struct {
Config *models.Config
Db *gorm.DB
}
2019-10-10 17:47:19 +03:00
var userAliases sync.Map
2019-07-06 18:53:20 +03:00
2020-02-20 16:28:55 +03:00
func (srv *AliasService) Init() {}
func (srv *AliasService) LoadUserAliases(userId string) error {
2019-07-06 18:53:20 +03:00
var aliases []*models.Alias
if err := srv.Db.
Where(&models.Alias{UserID: userId}).
Find(&aliases).Error; err != nil {
return err
}
2019-10-10 17:47:19 +03:00
userAliases.Store(userId, aliases)
2019-07-06 18:53:20 +03:00
return nil
}
func (srv *AliasService) GetAliasOrDefault(userId string, summaryType uint8, value string) (string, error) {
2019-10-10 17:47:19 +03:00
if ua, ok := userAliases.Load(userId); ok {
for _, a := range ua.([]*models.Alias) {
2019-07-06 18:53:20 +03:00
if a.Type == summaryType && a.Value == value {
return a.Key, nil
}
}
return value, nil
}
2019-11-08 01:11:19 +03:00
return "", errors.New("user aliases not initialized")
2019-07-06 18:53:20 +03:00
}
func (src *AliasService) IsInitialized(userId string) bool {
2019-10-10 17:47:19 +03:00
if _, ok := userAliases.Load(userId); ok {
2019-07-06 18:53:20 +03:00
return true
}
return false
}