codeword/internal/repository/user_repository.go

97 lines
2.1 KiB
Go
Raw Normal View History

2023-12-29 11:30:20 +00:00
package repository
import (
"codeword/internal/models"
2023-12-29 12:41:26 +00:00
"context"
2023-12-31 12:22:03 +00:00
"encoding/json"
"fmt"
"github.com/go-redis/redis/v8"
"go.mongodb.org/mongo-driver/bson"
2023-12-29 12:41:26 +00:00
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/readpref"
2023-12-29 11:30:20 +00:00
"time"
)
2023-12-31 12:22:03 +00:00
type Deps struct {
Mdb *mongo.Collection
Rdb *redis.Client
2023-12-29 11:30:20 +00:00
}
2023-12-31 12:22:03 +00:00
type codewordRepository struct {
mdb *mongo.Collection
rdb *redis.Client
}
type userRepository struct {
mdb *mongo.Collection
}
func NewUserRepository(deps Deps) *userRepository {
return &userRepository{mdb: deps.Mdb}
}
func NewCodewordRepository(deps Deps) *codewordRepository {
return &codewordRepository{mdb: deps.Mdb, rdb: deps.Rdb}
}
func (r *userRepository) FindByEmail(ctx context.Context, email string) (*models.User, error) {
var user models.User
2023-12-29 18:02:50 +00:00
2023-12-31 12:22:03 +00:00
err := r.mdb.FindOne(ctx, bson.M{"email": email}).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
return nil, nil
}
return nil, err
}
return &user, nil
2023-12-29 11:30:20 +00:00
}
2023-12-31 12:22:03 +00:00
func (r *codewordRepository) StoreRecoveryRecord(ctx context.Context, userID string, email string, key []byte) error {
record := models.RecoveryRecord{
UserID: userID,
Email: email,
Key: string(key),
CreatedAt: time.Now(),
}
_, err := r.mdb.InsertOne(ctx, record)
if err != nil {
return err
}
return nil
2023-12-29 11:30:20 +00:00
}
2023-12-31 12:22:03 +00:00
func (r *codewordRepository) InsertToQueue(ctx context.Context, userID string, email string, key []byte) error {
task := models.RecoveryRecord{
UserID: userID,
Email: email,
Key: string(key),
CreatedAt: time.Now(),
}
taskBytes, err := json.Marshal(task)
if err != nil {
return err
}
uniqKey := fmt.Sprintf("needRecovery:%d", time.Now().UnixNano())
if err := r.rdb.Set(ctx, uniqKey, taskBytes, 0).Err(); err != nil {
return err
}
2023-12-29 11:30:20 +00:00
return nil
}
2023-12-31 12:22:03 +00:00
func (r *codewordRepository) GetRecoveryRecord(ctx context.Context, key string) (*models.RestoreRequest, error) {
return &models.RestoreRequest{UserID: "123", Sign: key, CreatedAt: time.Now()}, nil
2023-12-29 11:30:20 +00:00
}
2023-12-31 12:22:03 +00:00
func (r *codewordRepository) Ping(ctx context.Context) error {
return r.mdb.Database().Client().Ping(ctx, readpref.Primary())
2023-12-29 11:30:20 +00:00
}