You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.1 KiB
53 lines
1.1 KiB
3 years ago
|
package mongodb
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
"gitea.russia9.dev/Russia9/chatwars-spy/pkg/domain"
|
||
|
"go.mongodb.org/mongo-driver/bson"
|
||
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
func NewUserRepo(database *mongo.Database) domain.UserRepo {
|
||
|
return &userRepo{Collection: database.Collection("users")}
|
||
|
}
|
||
|
|
||
|
type userRepo struct {
|
||
|
Collection *mongo.Collection
|
||
|
}
|
||
|
|
||
|
func (r *userRepo) Store(ctx context.Context, object *domain.User) error {
|
||
|
cursor := r.Collection.FindOne(ctx, bson.M{"_id": object.ID})
|
||
|
if errors.Is(cursor.Err(), mongo.ErrNoDocuments) {
|
||
|
object.FirstSeen = time.Now()
|
||
|
object.LastSeen = time.Now()
|
||
|
_, err := r.Collection.InsertOne(ctx, object)
|
||
|
return err
|
||
|
} else if cursor.Err() != nil {
|
||
|
return cursor.Err()
|
||
|
}
|
||
|
|
||
|
// Get old user
|
||
|
var old domain.User
|
||
|
err := cursor.Decode(&old)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
// Get old guild if empty
|
||
|
if object.Guild == "" {
|
||
|
object.Guild = old.Guild
|
||
|
}
|
||
|
|
||
|
// Set old source
|
||
|
object.Source = old.Source
|
||
|
|
||
|
// Set LastSeen date
|
||
|
object.LastSeen = time.Now()
|
||
|
|
||
|
// Update object in DB
|
||
|
_, err = r.Collection.ReplaceOne(ctx, bson.M{"_id": object.ID}, object)
|
||
|
return err
|
||
|
}
|