-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonarch.go
More file actions
executable file
·54 lines (43 loc) · 1.07 KB
/
monarch.go
File metadata and controls
executable file
·54 lines (43 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package monarch
import (
"context"
"sync"
"time"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
type ConnOptions func(*options.ClientOptions) error
type Connection struct {
client *mongo.Client
}
type Monarch struct {
conn *Connection
db *mongo.Database
cacheStore *sync.Map
}
func Connect(url string, opts ...ConnOptions) (*Connection, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
options := options.Client()
options = options.ApplyURI(url)
options = options.SetRegistry(mongoRegistry)
for _, opt := range opts {
if err := opt(options); err != nil {
return nil, err
}
}
client, err := mongo.Connect(options)
if err != nil {
return nil, err
}
if err := client.Ping(ctx, nil); err != nil {
return nil, err
}
return &Connection{client: client}, nil
}
func New(c *Connection) *Monarch {
return &Monarch{conn: c, cacheStore: &sync.Map{}, db: c.client.Database("monarch")}
}
func (m *Monarch) UseDB(db string) {
m.db = m.conn.client.Database(db)
}