diff options
Diffstat (limited to 'db/mongodb/client.go')
-rw-r--r-- | db/mongodb/client.go | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/db/mongodb/client.go b/db/mongodb/client.go new file mode 100644 index 0000000..98369b9 --- /dev/null +++ b/db/mongodb/client.go | |||
@@ -0,0 +1,90 @@ | |||
1 | package mongodb | ||
2 | |||
3 | import ( | ||
4 | "context" | ||
5 | "net/url" | ||
6 | |||
7 | "go.mongodb.org/mongo-driver/bson" | ||
8 | "go.mongodb.org/mongo-driver/mongo" | ||
9 | "go.mongodb.org/mongo-driver/mongo/options" | ||
10 | "go.mongodb.org/mongo-driver/x/mongo/driver/connstring" | ||
11 | |||
12 | "code.crute.us/mcrute/golib/vault" | ||
13 | ) | ||
14 | |||
15 | type Mongo struct { | ||
16 | client *mongo.Client | ||
17 | db *mongo.Database | ||
18 | } | ||
19 | |||
20 | func Connect(ctx context.Context, uri, materialSet string) (*Mongo, error) { | ||
21 | db := &Mongo{} | ||
22 | |||
23 | cred, err := vault.GetVaultDatabase(materialSet) | ||
24 | if err != nil { | ||
25 | return nil, err | ||
26 | } | ||
27 | |||
28 | u, err := url.Parse(uri) | ||
29 | if err != nil { | ||
30 | return nil, err | ||
31 | } | ||
32 | u.User = url.UserPassword(cred.Username, cred.Password) | ||
33 | |||
34 | cs, err := connstring.ParseAndValidate(u.String()) | ||
35 | if err != nil { | ||
36 | return nil, err | ||
37 | } | ||
38 | |||
39 | client, err := mongo.Connect(ctx, options.Client().ApplyURI(u.String())) | ||
40 | if err != nil { | ||
41 | return nil, err | ||
42 | } | ||
43 | |||
44 | db.client = client | ||
45 | db.db = client.Database(cs.Database) | ||
46 | |||
47 | return db, nil | ||
48 | } | ||
49 | |||
50 | func (m *Mongo) Collection(name string) *mongo.Collection { | ||
51 | return m.db.Collection(name) | ||
52 | } | ||
53 | |||
54 | func (m *Mongo) FindAll(ctx context.Context, cn string, out interface{}) error { | ||
55 | res, err := m.db.Collection(cn).Find(ctx, bson.D{}) | ||
56 | if err != nil { | ||
57 | return err | ||
58 | } | ||
59 | |||
60 | if err = res.All(ctx, out); err != nil { | ||
61 | return err | ||
62 | } | ||
63 | |||
64 | return nil | ||
65 | } | ||
66 | |||
67 | func (m *Mongo) FindOneById(ctx context.Context, cn string, id string, out interface{}) error { | ||
68 | if err := m.db.Collection(cn).FindOne(ctx, bson.M{"_id": id}).Decode(out); err != nil { | ||
69 | return err | ||
70 | } | ||
71 | |||
72 | return nil | ||
73 | } | ||
74 | |||
75 | func (m *Mongo) InsertOne(ctx context.Context, cn string, in interface{}) error { | ||
76 | _, err := m.db.Collection(cn).InsertOne(ctx, in) | ||
77 | if err != nil { | ||
78 | return err | ||
79 | } | ||
80 | |||
81 | return nil | ||
82 | } | ||
83 | |||
84 | func (m *Mongo) ReplaceOneById(ctx context.Context, cn string, id string, in interface{}) error { | ||
85 | if _, err := m.db.Collection(cn).ReplaceOne(ctx, bson.M{"_id": id}, in); err != nil { | ||
86 | return err | ||
87 | } | ||
88 | |||
89 | return nil | ||
90 | } | ||