@@ -2,42 +2,37 @@ package mongodb
22
33import (
44 "context"
5- "fmt"
65 "time"
76
87 "go.mongodb.org/mongo-driver/mongo"
98 "go.mongodb.org/mongo-driver/mongo/options"
109)
1110
12- // DBConfig contains the database configuration
13- type DBConfig struct {
14- Host string `mapstructure:"host" default:"localhost"`
15- Port string `mapstructure:"port" default:"27017"`
11+ // Config contains the database configurations.
12+ type Config struct {
13+ // URI should be valid MongodDB connection string.
14+ // https://www.mongodb.com/docs/manual/reference/connection-string/
15+ URI string `mapstructure:"uri" default:"mongodb://localhost:27017"`
16+
17+ // Name should be the name of the database to use.
1618 Name string `mapstructure:"name" default:"entropy"`
17- }
1819
19- // New returns the database instance
20- func New (config * DBConfig ) (* mongo.Database , error ) {
21- uri := fmt .Sprintf (
22- "mongodb://%s:%s/%s" ,
23- config .Host ,
24- config .Port ,
25- config .Name ,
26- )
20+ // PingTimeout decides the maximum time to wait for ping response.
21+ PingTimeout time.Duration `mapstructure:"ping_timeout" default:"3s"`
22+ }
2723
28- client , err := mongo .Connect (context .TODO (), options .Client ().ApplyURI (uri ))
24+ // Connect returns the database instance
25+ func Connect (cfg Config ) (* mongo.Database , error ) {
26+ client , err := mongo .Connect (context .TODO (), options .Client ().ApplyURI (cfg .URI ))
2927 if err != nil {
3028 return nil , err
3129 }
3230
33- pingCtx , pingCancel := context .WithTimeout (context .TODO (), time . Second * 5 )
31+ pingCtx , pingCancel := context .WithTimeout (context .TODO (), cfg . PingTimeout )
3432 defer pingCancel ()
35-
36- err = client .Ping (pingCtx , nil )
37-
38- if err != nil {
33+ if err := client .Ping (pingCtx , nil ); err != nil {
3934 return nil , err
4035 }
4136
42- return client .Database (config .Name ), nil
37+ return client .Database (cfg .Name ), nil
4338}
0 commit comments