2024-03-31 18:23:50 +00:00
|
|
|
package repository
|
2024-03-31 20:04:15 +00:00
|
|
|
|
2024-04-01 13:18:16 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
|
|
"go.mongodb.org/mongo-driver/bson/primitive"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"mailnotifier/internal/models"
|
|
|
|
)
|
2024-03-31 20:04:15 +00:00
|
|
|
|
|
|
|
type Repository struct {
|
2024-04-07 17:54:54 +00:00
|
|
|
mdb *mongo.Collection
|
|
|
|
//welcomeChan chan models.Message
|
2024-03-31 20:04:15 +00:00
|
|
|
}
|
|
|
|
|
2024-04-07 17:54:54 +00:00
|
|
|
func NewRepository(mdb *mongo.Collection) *Repository {
|
2024-03-31 20:04:15 +00:00
|
|
|
return &Repository{
|
2024-04-07 17:54:54 +00:00
|
|
|
mdb: mdb,
|
2024-03-31 20:04:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-01 13:18:16 +00:00
|
|
|
// записываем каждый месседж по одному
|
|
|
|
func (r *Repository) Insert(ctx context.Context, mes models.Message) error {
|
|
|
|
mes.ID = primitive.NewObjectID()
|
|
|
|
_, err := r.mdb.InsertOne(ctx, mes)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-04-07 17:54:54 +00:00
|
|
|
//r.welcomeChan <- mes
|
2024-04-02 14:46:05 +00:00
|
|
|
|
2024-04-01 13:18:16 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-04-05 14:58:26 +00:00
|
|
|
// todo стоит лучше передавать фильтр сразу для того чтобы разгрузить запрос
|
2024-04-01 13:18:16 +00:00
|
|
|
// получаем сразу все в tools метод распределения
|
|
|
|
func (r *Repository) GetMany(ctx context.Context) ([]models.Message, error) {
|
|
|
|
cursor, err := r.mdb.Find(ctx, bson.D{})
|
|
|
|
if err != nil {
|
2024-04-02 16:25:47 +00:00
|
|
|
if err == mongo.ErrNoDocuments {
|
|
|
|
return []models.Message{}, nil
|
|
|
|
}
|
2024-04-01 13:18:16 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer cursor.Close(ctx)
|
|
|
|
|
|
|
|
var messages []models.Message
|
|
|
|
if err := cursor.All(ctx, &messages); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-03-31 20:04:15 +00:00
|
|
|
|
2024-04-01 13:18:16 +00:00
|
|
|
return messages, nil
|
|
|
|
}
|
2024-04-02 14:46:05 +00:00
|
|
|
|
|
|
|
// апдейтим то что отправили на почту
|
|
|
|
func (r *Repository) Update(ctx context.Context, message models.Message) error {
|
|
|
|
filter := bson.M{"_id": message.ID}
|
|
|
|
update := bson.M{
|
|
|
|
"$set": bson.M{
|
|
|
|
"sendRegistration": message.SendRegistration,
|
|
|
|
"sendNoneCreated": message.SendNoneCreated,
|
|
|
|
"sendUnpublished": message.SendUnpublished,
|
|
|
|
"sendPaid": message.SendPaid,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err := r.mdb.UpdateOne(ctx, filter, update)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|