106 lines
2.3 KiB
Go
106 lines
2.3 KiB
Go
package mongo
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.acooldomain.co/server-manager/backend-kubernetes-go/dbhandler"
|
|
"git.acooldomain.co/server-manager/backend-kubernetes-go/models"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type User struct {
|
|
Username string `bson:"username"`
|
|
Email string `bson:"email"`
|
|
Nickname string `bson:"nickname"`
|
|
}
|
|
|
|
type UsersDbHandler struct {
|
|
dbhandler.UsersDBHandler
|
|
collection *mongo.Collection
|
|
}
|
|
|
|
func (self *UsersDbHandler) GetUser(ctx context.Context, username string) (*dbhandler.User, error) {
|
|
var user User
|
|
|
|
err := self.collection.FindOne(ctx, bson.M{"username": username}).Decode(&user)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &dbhandler.User{
|
|
Username: user.Username,
|
|
Email: user.Email,
|
|
Nickname: user.Nickname,
|
|
}, nil
|
|
}
|
|
|
|
func (self *UsersDbHandler) ListUsers(ctx context.Context) ([]dbhandler.User, error) {
|
|
cursor, err := self.collection.Find(ctx, bson.M{})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer cursor.Close(ctx)
|
|
|
|
var users []User
|
|
|
|
cursor.All(nil, &users)
|
|
|
|
response := make([]dbhandler.User, len(users))
|
|
|
|
for i, user := range users {
|
|
response[i] = dbhandler.User{
|
|
Username: user.Username,
|
|
Nickname: user.Nickname,
|
|
Email: user.Email,
|
|
}
|
|
}
|
|
|
|
return response, nil
|
|
}
|
|
|
|
func (self *UsersDbHandler) CreateUser(ctx context.Context, user dbhandler.User) error {
|
|
_, err := self.collection.InsertOne(ctx, &User{
|
|
Username: user.Username,
|
|
Email: user.Email,
|
|
Nickname: user.Nickname,
|
|
}, &options.InsertOneOptions{})
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (self *UsersDbHandler) DeleteUser(ctx context.Context, username string) error {
|
|
_, err := self.collection.DeleteOne(ctx, bson.M{"username": username})
|
|
|
|
return err
|
|
}
|
|
|
|
func NewUsersHandler(config models.MongoDBConfig) (*UsersDbHandler, error) {
|
|
clientOptions := options.Client().ApplyURI(config.Url).SetAuth(options.Credential{
|
|
Username: config.Username,
|
|
Password: config.Password,
|
|
})
|
|
|
|
ctx, cancel := context.WithTimeoutCause(context.Background(), 30*time.Second, fmt.Errorf("Timeout"))
|
|
defer cancel()
|
|
|
|
client, err := mongo.Connect(ctx, clientOptions)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &UsersDbHandler{
|
|
collection: client.Database(config.Database).Collection(config.Collection),
|
|
}, nil
|
|
}
|