package storage import ( "context" "fmt" "github.com/spf13/viper" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type MongoDBStorage struct { *mongo.Client DbName string Collections map[string]string } func NewMongoDBStorage(cfg *viper.Viper) (MongoDBStorage, error) { var ( mongodb_uri = cfg.GetString("storage.db.mongodb.uri") mongodb_host = cfg.GetString("storage.db.mongodb.host") mongodb_port = cfg.GetString("storage.db.mongodb.port") mongodb_dbname = cfg.GetString("storage.db.mongodb.db_name") mongodb_incentives_subscriptions = cfg.GetString("storage.db.mongodb.collections.incentives_subscriptions") mongodb_proofs = cfg.GetString("storage.db.mongodb.collections.proofs") ) if mongodb_uri == "" { mongodb_uri = fmt.Sprintf("mongodb://%s:%s/%s", mongodb_host, mongodb_port, mongodb_dbname) } client, err := mongo.NewClient(options.Client().ApplyURI(mongodb_uri)) if err != nil { return MongoDBStorage{}, err } err = client.Connect(context.TODO()) if err != nil { return MongoDBStorage{}, err } storage := MongoDBStorage{ Client: client, DbName: mongodb_dbname, Collections: map[string]string{ "incentives_subscriptions": mongodb_incentives_subscriptions, "proofs": mongodb_proofs, }, } return storage, nil } func (s MongoDBStorage) GetUserSubscriptions(userid string) ([]IncentiveSubscription, error) { collection := s.Client.Database(s.DbName).Collection(s.Collections["incentives_subscriptions"]) subscriptions := []IncentiveSubscription{} findOptions := options.Find() cur, err := collection.Find(context.TODO(), bson.M{"user_id": userid}, findOptions) if err != nil { return nil, err } for cur.Next(context.TODO()) { var subscription IncentiveSubscription if err := cur.Decode(&subscription); err != nil { return subscriptions, err } subscriptions = append(subscriptions, subscription) } return subscriptions, nil } func (s MongoDBStorage) SubscribeIncentive(incentive_subscription IncentiveSubscription) error { collection := s.Client.Database(s.DbName).Collection(s.Collections["incentives_subscriptions"]) if _, err := collection.InsertOne(context.TODO(), incentive_subscription); err != nil { return err } return nil }