refactor: narrow auth service to smaller units
Easier for testing, and omits need for full dep injection for pusher service, where we passed in nil for deps dangerously.
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type SessionReader interface {
|
||||
// GetSession returns ErrSessionNotFound if no valid session.
|
||||
GetSession(ctx context.Context, sessionToken string) (*Session, error)
|
||||
}
|
||||
|
||||
type sessionReaderImpl struct {
|
||||
redisClient *redis.Client
|
||||
}
|
||||
|
||||
// newSessionReader returns the concrete reader. Used by NewAuthService to
|
||||
// embed without going through the SessionReader interface (which would hide
|
||||
// redisClient from the rest of authServiceImpl).
|
||||
func newSessionReader(redisClient *redis.Client) *sessionReaderImpl {
|
||||
return &sessionReaderImpl{redisClient: redisClient}
|
||||
}
|
||||
|
||||
func NewSessionReader(redisClient *redis.Client) SessionReader {
|
||||
return newSessionReader(redisClient)
|
||||
}
|
||||
|
||||
func (r *sessionReaderImpl) GetSession(ctx context.Context, token string) (*Session, error) {
|
||||
sessionInfo, err := r.redisClient.Get(ctx, token).Result()
|
||||
if err != nil {
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, ErrSessionNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("error getting session: %w", err)
|
||||
}
|
||||
|
||||
var session Session
|
||||
err = json.Unmarshal([]byte(sessionInfo), &session)
|
||||
|
||||
return &session, nil
|
||||
}
|
||||
Reference in New Issue
Block a user