Sharing: Implement session update #18

Signed-off-by: Michael Mayer <michael@liquidbytes.net>
This commit is contained in:
Michael Mayer 2020-06-24 17:40:09 +02:00
parent 474d9cd657
commit faa1ec2e4b
2 changed files with 67 additions and 2 deletions

View file

@ -2,6 +2,7 @@ package session
import (
"encoding/json"
"fmt"
"io/ioutil"
gc "github.com/patrickmn/go-cache"
@ -13,18 +14,34 @@ func (s *Session) Create(data interface{}) string {
log.Debugf("session: created")
if err := s.Save(); err != nil {
log.Errorf("session: %s", err)
log.Errorf("session: %s (create)", err)
}
return token
}
func (s *Session) Update(token string, data interface{}) error {
if _, found := s.cache.Get(token); !found {
return fmt.Errorf("session: %s not found (update)", token)
}
s.cache.Set(token, data, gc.DefaultExpiration)
log.Debugf("session: updated")
if err := s.Save(); err != nil {
return fmt.Errorf("session: %s (update)", err.Error())
}
return nil
}
func (s *Session) Delete(token string) {
s.cache.Delete(token)
log.Debugf("session: deleted")
if err := s.Save(); err != nil {
log.Errorf("session: %s", err)
log.Errorf("session: %s (delete)", err)
}
}

View file

@ -14,6 +14,54 @@ func TestSession_Create(t *testing.T) {
assert.Equal(t, 48, len(token))
}
func TestSession_Update(t *testing.T) {
s := New(time.Hour, "testdata")
type Data struct {
Key string
}
data := Data{
Key: "VALUE",
}
randomToken := Token()
assert.Equal(t, 48, len(randomToken))
if _, found := s.Get(randomToken); found {
t.Fatalf("session %s should not exist", randomToken)
}
if err := s.Update(randomToken, data); err == nil {
t.Fatalf("update should fail for unknown token %s", randomToken)
}
token := s.Create(data)
assert.Equal(t, 48, len(token))
hit, found := s.Get(token)
if!found {
t.Fatalf("session %s should exist", token)
}
cachedData := hit.(Data)
assert.Equal(t, cachedData, data)
newData := Data{
Key: "NEW",
}
if err := s.Update(token, newData); err != nil {
t.Fatalf(err.Error())
}
if _, found := s.Get(token); !found {
t.Fatalf("session %s should exist", token)
}
}
func TestSession_Delete(t *testing.T) {
s := New(time.Hour, "testdata")
s.Delete("abc")