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

48 lines
959 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"
"github.com/n1try/wakapi/models"
)
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
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
}