2019-07-06 18:53:20 +03:00
|
|
|
package services
|
|
|
|
|
|
|
|
import (
|
2020-09-29 19:55:07 +03:00
|
|
|
"github.com/muety/wakapi/config"
|
2020-11-01 18:56:36 +03:00
|
|
|
"github.com/muety/wakapi/repositories"
|
2019-10-10 17:47:19 +03:00
|
|
|
"sync"
|
2019-07-06 18:53:20 +03:00
|
|
|
|
2020-03-31 13:22:17 +03:00
|
|
|
"github.com/muety/wakapi/models"
|
2019-07-06 18:53:20 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type AliasService struct {
|
2020-11-01 18:56:36 +03:00
|
|
|
config *config.Config
|
|
|
|
repository *repositories.AliasRepository
|
2019-07-06 18:53:20 +03:00
|
|
|
}
|
|
|
|
|
2020-11-01 18:56:36 +03:00
|
|
|
func NewAliasService(aliasRepo *repositories.AliasRepository) *AliasService {
|
2020-05-24 18:32:26 +03:00
|
|
|
return &AliasService{
|
2020-11-01 18:56:36 +03:00
|
|
|
config: config.Get(),
|
|
|
|
repository: aliasRepo,
|
2020-05-24 18:32:26 +03:00
|
|
|
}
|
|
|
|
}
|
2019-07-06 18:53:20 +03:00
|
|
|
|
2020-05-24 18:32:26 +03:00
|
|
|
var userAliases sync.Map
|
2020-02-20 16:28:55 +03:00
|
|
|
|
2019-07-07 11:32:28 +03:00
|
|
|
func (srv *AliasService) LoadUserAliases(userId string) error {
|
2020-11-01 18:56:36 +03:00
|
|
|
aliases, err := srv.repository.GetByUser(userId)
|
|
|
|
if err == nil {
|
|
|
|
userAliases.Store(userId, aliases)
|
2019-07-06 18:53:20 +03:00
|
|
|
}
|
2020-11-01 18:56:36 +03:00
|
|
|
return err
|
2019-07-06 18:53:20 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *AliasService) GetAliasOrDefault(userId string, summaryType uint8, value string) (string, error) {
|
2020-11-01 18:03:30 +03:00
|
|
|
if !srv.IsInitialized(userId) {
|
|
|
|
if err := srv.LoadUserAliases(userId); err != nil {
|
|
|
|
return "", err
|
2019-07-06 18:53:20 +03:00
|
|
|
}
|
|
|
|
}
|
2020-11-01 18:03:30 +03:00
|
|
|
|
|
|
|
aliases, _ := userAliases.Load(userId)
|
|
|
|
for _, a := range aliases.([]*models.Alias) {
|
|
|
|
if a.Type == summaryType && a.Value == value {
|
|
|
|
return a.Key, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return value, nil
|
2019-07-06 18:53:20 +03:00
|
|
|
}
|
|
|
|
|
2020-05-30 21:41:27 +03:00
|
|
|
func (srv *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
|
|
|
|
}
|