2019-12-28 09:48:36 +01:00
|
|
|
package session
|
|
|
|
|
|
|
|
import (
|
2020-06-24 17:40:09 +02:00
|
|
|
"fmt"
|
2019-12-28 09:48:36 +01:00
|
|
|
|
|
|
|
gc "github.com/patrickmn/go-cache"
|
|
|
|
)
|
|
|
|
|
2020-06-25 01:20:58 +02:00
|
|
|
func (s *Session) Create(data Data) string {
|
2020-06-25 14:54:04 +02:00
|
|
|
id := NewID()
|
|
|
|
s.cache.Set(id, data, gc.DefaultExpiration)
|
2019-12-28 09:48:36 +01:00
|
|
|
log.Debugf("session: created")
|
2020-04-20 13:50:28 +02:00
|
|
|
|
|
|
|
if err := s.Save(); err != nil {
|
2020-06-24 17:40:09 +02:00
|
|
|
log.Errorf("session: %s (create)", err)
|
2020-04-20 13:50:28 +02:00
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
return id
|
2019-12-28 09:48:36 +01:00
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
func (s *Session) Update(id string, data Data) error {
|
|
|
|
if id == "" {
|
|
|
|
return fmt.Errorf("session: empty id")
|
2020-06-24 17:40:09 +02:00
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
if _, found := s.cache.Get(id); !found {
|
|
|
|
return fmt.Errorf("session: %s not found (update)", id)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.cache.Set(id, data, gc.DefaultExpiration)
|
2020-06-24 17:40:09 +02:00
|
|
|
|
|
|
|
log.Debugf("session: updated")
|
|
|
|
|
|
|
|
if err := s.Save(); err != nil {
|
|
|
|
return fmt.Errorf("session: %s (update)", err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
func (s *Session) Delete(id string) {
|
|
|
|
s.cache.Delete(id)
|
2019-12-28 09:48:36 +01:00
|
|
|
log.Debugf("session: deleted")
|
2020-04-20 13:50:28 +02:00
|
|
|
|
|
|
|
if err := s.Save(); err != nil {
|
2020-06-24 17:40:09 +02:00
|
|
|
log.Errorf("session: %s (delete)", err)
|
2020-04-20 13:50:28 +02:00
|
|
|
}
|
2019-12-28 09:48:36 +01:00
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
func (s *Session) Get(id string) Data {
|
|
|
|
if id == "" {
|
|
|
|
return Data{}
|
2020-06-25 01:20:58 +02:00
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
if hit, ok := s.cache.Get(id); ok {
|
|
|
|
return hit.(Data)
|
|
|
|
}
|
|
|
|
|
|
|
|
return Data{}
|
2019-12-28 09:48:36 +01:00
|
|
|
}
|
|
|
|
|
2020-06-25 14:54:04 +02:00
|
|
|
func (s *Session) Exists(id string) bool {
|
|
|
|
_, found := s.cache.Get(id)
|
2019-12-28 09:48:36 +01:00
|
|
|
|
|
|
|
return found
|
|
|
|
}
|