Capstone/ui/db/user.go

87 lines
2.0 KiB
Go
Raw Normal View History

2023-10-28 14:42:29 -04:00
package db
import (
"context"
"git.preston-baxter.com/Preston_PLB/capstone/frontend-service/config"
"git.preston-baxter.com/Preston_PLB/capstone/frontend-service/db/models"
"go.mongodb.org/mongo-driver/bson"
2023-11-02 19:23:07 -04:00
"go.mongodb.org/mongo-driver/bson/primitive"
2023-10-28 17:50:44 -04:00
"go.mongodb.org/mongo-driver/mongo"
2023-10-28 14:42:29 -04:00
"go.mongodb.org/mongo-driver/mongo/options"
)
2023-11-14 13:48:12 -05:00
//seraches for a single user by email address
2023-10-28 14:42:29 -04:00
func (db *DB) FindUserByEmail(email string) (*models.User, error) {
conf := config.Config()
opts := options.FindOne()
2023-10-31 21:31:26 -04:00
res := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).FindOne(context.Background(), bson.M{"email": email, "obj_info.ent": models.USER_TYPE}, opts)
2023-10-28 14:42:29 -04:00
if res.Err() != nil {
2023-10-28 17:50:44 -04:00
if res.Err() == mongo.ErrNoDocuments {
return nil, nil
}
2023-10-28 14:42:29 -04:00
return nil, res.Err()
}
user := &models.User{}
err := res.Decode(user)
if err != nil {
return nil, err
}
return user, nil
}
2023-11-14 13:48:12 -05:00
//find user by its unique id
2023-10-28 14:42:29 -04:00
func (db *DB) FindUserById(id string) (*models.User, error) {
conf := config.Config()
opts := options.FindOne()
2023-11-02 19:23:07 -04:00
objId, err := primitive.ObjectIDFromHex(id)
if err != nil {
return nil, err
}
res := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).FindOne(context.Background(), bson.M{"_id": objId , "obj_info.ent": models.USER_TYPE}, opts)
2023-10-28 14:42:29 -04:00
if res.Err() != nil {
2023-10-28 17:50:44 -04:00
if res.Err() == mongo.ErrNoDocuments {
return nil, nil
}
2023-10-28 14:42:29 -04:00
return nil, res.Err()
}
user := &models.User{}
2023-11-02 19:23:07 -04:00
err = res.Decode(user)
2023-10-28 14:42:29 -04:00
if err != nil {
return nil, err
}
return user, nil
}
2023-11-14 13:48:12 -05:00
//returns all users
2023-10-28 14:42:29 -04:00
func (db *DB) FindAllUsers() ([]models.User, error) {
conf := config.Config()
opts := options.Find()
res, err := db.client.Database(conf.Mongo.EntDb).Collection(conf.Mongo.EntCol).Find(context.Background(), bson.M{"obj_info.ent": models.USER_TYPE}, opts)
2023-10-28 14:42:29 -04:00
if err != nil {
2023-10-28 17:50:44 -04:00
if err == mongo.ErrNoDocuments {
return nil, nil
}
2023-10-28 14:42:29 -04:00
return nil, res.Err()
}
users := []models.User{}
err = res.All(context.Background(), users)
if err != nil {
return nil, err
}
return users, nil
}