codeword/internal/repository/user_repository.go

99 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"
"github.com/go-redis/redis/v8"
2024-01-01 14:13:54 +00:00
"github.com/pioz/faker"
2023-12-31 12:22:03 +00:00
"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,
2024-01-03 13:50:11 +00:00
Key: key,
2023-12-31 12:22:03 +00:00
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 {
2024-01-01 14:13:54 +00:00
// todo не забыть убрать потом этот цикл
for i := 0; i < 10; i++ {
task := models.RecoveryRecord{
UserID: userID + faker.String(),
Email: email,
2024-01-03 13:50:11 +00:00
Key: key,
2024-01-01 14:13:54 +00:00
CreatedAt: time.Now(),
}
2023-12-31 12:22:03 +00:00
2024-01-01 14:13:54 +00:00
taskBytes, err := json.Marshal(task)
if err != nil {
return err
}
2023-12-31 12:22:03 +00:00
2024-01-01 14:13:54 +00:00
if err := r.rdb.LPush(ctx, "recoveryQueue", taskBytes).Err(); err != nil {
return err
}
2023-12-31 12:22:03 +00:00
}
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
}