some-automoderation/sessions/sessions_manager.go

70 lines
1.6 KiB
Go

package sessions
import (
"context"
"fmt"
"log"
"math/rand"
"github.com/redis/go-redis/v9"
)
type SessionData struct {
SessionId int64 `redis:"session_id"`
RoomId int64 `redis:"room_id"`
PersonId int64 `redis:"person_id"`
}
type SessionManagement interface {
Get(sessionId int64) SessionData
Save(roomId int64, personId int64) (int64, error)
}
var ctx = context.Background()
const sessionPrefix = "session"
func sessionIdToKey(sessionId int64) string {
return fmt.Sprintf("%s:%d", sessionPrefix, sessionId)
}
type RedisSM struct {
Rdb *redis.Client
}
func (redisSM RedisSM) Get(sessionId int64) SessionData {
var foundSession SessionData
err := redisSM.Rdb.HGetAll(ctx, sessionIdToKey(sessionId)).Scan(foundSession)
if err != nil {
log.Printf("> error reading %d", sessionId)
return SessionData{}
}
log.Printf("> successfully found %d %+v", sessionId, foundSession)
return foundSession
}
func (redisSM RedisSM) Save(roomId int64, personId int64) (int64, error) {
randId := rand.Int63()
newSession := SessionData{
SessionId: randId,
RoomId: roomId,
PersonId: personId,
}
err := redisSM.Rdb.HSet(ctx, sessionIdToKey(randId), newSession).Err()
if err != nil {
log.Printf("> error! saving session %+v %s", newSession, err)
return 0, fmt.Errorf("error saving new session: %+v with %s", newSession, err)
}
return randId, nil
}
type DummySM struct{}
func (d DummySM) Get(sessionId int64) SessionData {
log.Printf("get dummy session by %d", sessionId)
return SessionData{}
}
func (d DummySM) Save(roomId int64, personId int64) (int64, error) {
log.Printf("save dummy session with %d %d", roomId, personId)
return 1, nil
}