2022-01-21 06:48:07 +00:00
|
|
|
package mongodb
|
|
|
|
|
|
|
|
import (
|
2022-07-10 16:19:33 +00:00
|
|
|
"context"
|
2022-01-21 06:48:07 +00:00
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/authorizerdev/authorizer/server/db/models"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
|
|
)
|
|
|
|
|
|
|
|
// AddEnv to save environment information in database
|
2022-07-10 16:19:33 +00:00
|
|
|
func (p *provider) AddEnv(ctx context.Context, env models.Env) (models.Env, error) {
|
2022-01-21 06:48:07 +00:00
|
|
|
if env.ID == "" {
|
|
|
|
env.ID = uuid.New().String()
|
|
|
|
}
|
|
|
|
|
|
|
|
env.CreatedAt = time.Now().Unix()
|
|
|
|
env.UpdatedAt = time.Now().Unix()
|
|
|
|
env.Key = env.ID
|
|
|
|
configCollection := p.db.Collection(models.Collections.Env, options.Collection())
|
2022-07-10 16:19:33 +00:00
|
|
|
_, err := configCollection.InsertOne(ctx, env)
|
2022-01-21 06:48:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return env, err
|
|
|
|
}
|
|
|
|
return env, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdateEnv to update environment information in database
|
2022-07-10 16:19:33 +00:00
|
|
|
func (p *provider) UpdateEnv(ctx context.Context, env models.Env) (models.Env, error) {
|
2022-01-21 06:48:07 +00:00
|
|
|
env.UpdatedAt = time.Now().Unix()
|
|
|
|
configCollection := p.db.Collection(models.Collections.Env, options.Collection())
|
2022-07-10 16:19:33 +00:00
|
|
|
_, err := configCollection.UpdateOne(ctx, bson.M{"_id": bson.M{"$eq": env.ID}}, bson.M{"$set": env}, options.MergeUpdateOptions())
|
2022-01-21 06:48:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return env, err
|
|
|
|
}
|
|
|
|
return env, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetEnv to get environment information from database
|
2022-07-10 16:19:33 +00:00
|
|
|
func (p *provider) GetEnv(ctx context.Context) (models.Env, error) {
|
2022-01-21 06:48:07 +00:00
|
|
|
var env models.Env
|
|
|
|
configCollection := p.db.Collection(models.Collections.Env, options.Collection())
|
2022-07-10 16:19:33 +00:00
|
|
|
cursor, err := configCollection.Find(ctx, bson.M{}, options.Find())
|
2022-01-21 06:48:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return env, err
|
|
|
|
}
|
2022-07-10 16:19:33 +00:00
|
|
|
defer cursor.Close(ctx)
|
2022-01-21 06:48:07 +00:00
|
|
|
|
|
|
|
for cursor.Next(nil) {
|
|
|
|
err := cursor.Decode(&env)
|
|
|
|
if err != nil {
|
|
|
|
return env, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if env.ID == "" {
|
|
|
|
return env, fmt.Errorf("config not found")
|
|
|
|
}
|
|
|
|
|
|
|
|
return env, nil
|
|
|
|
}
|