|
| 1 | +package mongodb |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "github.com/Zondax/zindexer/connections/database" |
| 7 | + "go.uber.org/zap" |
| 8 | + "time" |
| 9 | + |
| 10 | + "go.mongodb.org/mongo-driver/bson" |
| 11 | + "go.mongodb.org/mongo-driver/mongo" |
| 12 | + "go.mongodb.org/mongo-driver/mongo/options" |
| 13 | + "go.mongodb.org/mongo-driver/mongo/readpref" |
| 14 | +) |
| 15 | + |
| 16 | +type MongoConnection struct { |
| 17 | + db *mongo.Client |
| 18 | +} |
| 19 | + |
| 20 | +func NewMongoConnection(params *database.DBConnectionParams) (*MongoConnection, error) { |
| 21 | + uri := params.URI |
| 22 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 23 | + defer cancel() |
| 24 | + |
| 25 | + client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri)) |
| 26 | + if err != nil { |
| 27 | + return nil, err |
| 28 | + } |
| 29 | + |
| 30 | + // Ping the primary |
| 31 | + if err := client.Ping(ctx, readpref.Primary()); err != nil { |
| 32 | + return nil, err |
| 33 | + } |
| 34 | + |
| 35 | + return &MongoConnection{db: client}, nil |
| 36 | +} |
| 37 | + |
| 38 | +func (c *MongoConnection) GetDB() *mongo.Client { |
| 39 | + return c.db |
| 40 | +} |
| 41 | + |
| 42 | +func Connect(params *database.DBConnectionParams) (*mongo.Client, error) { |
| 43 | + conn, err := NewMongoConnection(params) |
| 44 | + if err != nil { |
| 45 | + return nil, err |
| 46 | + } |
| 47 | + |
| 48 | + return conn.GetDB(), nil |
| 49 | +} |
| 50 | + |
| 51 | +func (c *MongoConnection) GetMongoDoc(collection *mongo.Collection, docId string) (bson.M, error) { |
| 52 | + zap.S().Debug("document with id:%v \n", docId) |
| 53 | + opts := options.FindOne() |
| 54 | + var result bson.M |
| 55 | + readErr := collection.FindOne( |
| 56 | + context.TODO(), |
| 57 | + bson.D{{Key: "_id", Value: docId}}, |
| 58 | + opts, |
| 59 | + ).Decode(&result) |
| 60 | + |
| 61 | + if readErr != nil { |
| 62 | + // ErrNoDocuments means that the filter did not match any documents in |
| 63 | + // the collection. |
| 64 | + if readErr == mongo.ErrNoDocuments { |
| 65 | + return nil, fmt.Errorf("no document found") |
| 66 | + } |
| 67 | + return nil, readErr |
| 68 | + } |
| 69 | + |
| 70 | + return result, nil |
| 71 | +} |
0 commit comments