cds-web/dao/users.go
2022-10-09 02:15:25 +02:00

113 lines
2.5 KiB
Go

package dao
import (
"cds/models"
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
func GetByDiscord(id string) (user *models.User, err error) {
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("users")
var result models.User
err = coll.FindOne(context.TODO(), bson.D{{"userId", id}}).Decode(&result)
if err != nil {
return nil, err
} else {
return &result, nil
}
}
func GetBySteam(id string) (user *models.User, err error) {
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("users")
var result models.User
err = coll.FindOne(context.TODO(), bson.D{{"steamId", id}}).Decode(&result)
if err != nil {
return nil, err
} else {
return &result, nil
}
}
func GetById(id string) (user *models.User, err error) {
db, _ := get()
objectId, err := primitive.ObjectIDFromHex(id)
defer disconnect(db.Client())
coll := db.Collection("users")
var result models.User
err = coll.FindOne(context.TODO(), bson.D{{"_id", objectId}}).Decode(&result)
if err != nil {
return nil, err
} else {
return &result, nil
}
}
func CreateUser(user *models.User) (id string, err error) {
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("users")
idDb, err := coll.InsertOne(context.TODO(), user)
id = fmt.Sprint(idDb.InsertedID)
return id, err
}
func AddSteam(discord string, steam string) error {
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("users")
update := bson.D{{"$set", bson.D{{"steamId", steam}}}}
var result bson.M
err := coll.FindOneAndUpdate(context.TODO(), bson.D{{"userId", discord}}, update).Decode(&result)
return err
}
func AddDiscord(steam string, discordId string, discordName string) error {
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("users")
update := bson.D{{"$set", bson.D{{"userId", discordId}, {"userName", discordName}}}}
var result bson.M
err := coll.FindOneAndUpdate(context.TODO(), bson.D{{"steamId", steam}}, update).Decode(&result)
return err
}
func RemoveSteam(steam string) error {
return nil
}
func RemoveDiscord(discord string) error {
return nil
}
func DeleteBySteam(steam string) error {
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("users")
_, err := coll.DeleteOne(context.TODO(), bson.D{{"steamId", steam}})
return err
}
func DeleteByDiscord(discord string) error {
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("users")
_, err := coll.DeleteOne(context.TODO(), bson.D{{"userId", discord}})
return err
}