package main import ( "context" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" ) type MongodbStorage struct { db *mongo.Client } func (m MongodbStorage) CreateUser(user *User) error { ctx := context.TODO() _, err := m.Collection("users").InsertOne(ctx, user) if err != nil { if e, ok := err.(mongo.WriteError); ok { log.Println("Error creating new user: ", e) return e } } return nil } func (m MongodbStorage) GetUsers() ([]User, error) { ctx := context.TODO() cur, err := m.Collection("users").Find(ctx, bson.D{}) if err != nil { log.Println("Error fetching users: ", err) return nil, err } var res []User err = cur.All(ctx, &res) if err != nil { log.Println("Error collection users to slice: ", err) return nil, err } return res, nil } func (m MongodbStorage) GetUserByName(username string) (*User, error) { ctx := context.TODO() res := m.Collection("users").FindOne(ctx, bson.D{{Key: "username", Value: username}}) if res.Err() != nil { return nil, res.Err() } var user User res.Decode(&user) return &user, nil } func (m MongodbStorage) GetUserByID(id primitive.ObjectID) (*User, error) { ctx := context.TODO() res := m.Collection("users").FindOne(ctx, bson.D{{Key: "_id", Value: id}}) if res.Err() != nil { return nil, res.Err() } var user User res.Decode(&user) return &user, nil } func (m MongodbStorage) UpdateUser(user *User) error { ctx := context.TODO() _, err := m.Collection("users").ReplaceOne(ctx, bson.D{{Key: "_id", Value: user.Id}}, user) return err } func (m MongodbStorage) DeleteUser(id primitive.ObjectID) error { ctx := context.TODO() _, err := m.Collection("users").DeleteOne(ctx, bson.D{{Key: "_id", Value: id}}) return err } func (m MongodbStorage) CreateSession(s *Session) error { ctx := context.TODO() _, err := m.Collection("sessions").InsertOne(ctx, s) if err != nil { if e, ok := err.(mongo.WriteError); ok { log.Println("Error creating new session: ", e) return e } } return nil } func (m MongodbStorage) GetSessionByToken(token string) (*Session, error) { ctx := context.TODO() res := m.Collection("sessions").FindOne(ctx, bson.D{{Key: "token", Value: token}}) if res.Err() != nil { return nil, res.Err() } var session Session res.Decode(&session) return &session, nil } func (m MongodbStorage) DeleteSession(id primitive.ObjectID) error { ctx := context.TODO() _, err := m.Collection("users").DeleteOne(ctx, bson.D{{Key: "_id", Value: id}}) return err } func (m MongodbStorage) Collection(col string) *mongo.Collection { return m.db.Database("nash").Collection(col) }