-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.go
88 lines (71 loc) · 2.28 KB
/
mongo.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
)
// mongoClient is a wrapper for a mongo client.
// this wrapper returns interfaces instead of concrete types.
// a real mongo client can exist inside this wrapper.
// the wrapper allows creation of a mock client that
// can be used in tests instead of the real wrapped client.
type mongoClient struct {
cl *mongo.Client
}
func (mc *mongoClient) Database(dbName string) DatabaseIface {
db := mc.cl.Database(dbName)
return &mongoDatabase{db: db}
}
func (mc *mongoClient) Connect(ctx context.Context) error {
err := mc.cl.Connect(ctx)
return err
}
// mongoDatabase is a wrapper for a *mongo.Database
type mongoDatabase struct {
db *mongo.Database
}
func (md *mongoDatabase) Collection(colName string) CollectionIface {
collection := md.db.Collection(colName)
return &mongoCollection{coll: collection}
}
// mongoCollection is a wrapper for a *mongo.Collection
type mongoCollection struct {
coll *mongo.Collection
}
func (mc *mongoCollection) InsertOne(ctx context.Context, document interface{}) (interface{}, error) {
id, err := mc.coll.InsertOne(ctx, document)
return id.InsertedID, err
}
func (mc *mongoCollection) FindOne(ctx context.Context, document interface{}) SingleResultIface {
result := mc.coll.FindOne(ctx, document)
return mongoSingleResult{res: result}
}
// mongoSingleResult is a wrapper for a *mongoSingleResult
type mongoSingleResult struct {
res *mongo.SingleResult
}
func (ms mongoSingleResult) Decode(v interface{}) error {
return ms.res.Decode(v)
}
// ClientIface describes methods on a mongo client
type ClientIface interface {
Database(string) DatabaseIface
Connect(ctx context.Context) error
}
// DatabaseIface describes methods on a mongo database
type DatabaseIface interface {
Collection(name string) CollectionIface
}
// CollectionIface describes methods on a mongo collection
type CollectionIface interface {
FindOne(context.Context, interface{}) SingleResultIface
InsertOne(context.Context, interface{}) (interface{}, error)
}
// SingleResultIface describes methods on a mongo single result
type SingleResultIface interface {
Decode(v interface{}) error
}
// schemaData is used to marshal to and fron bson.
type schemaData struct {
ID string `bson:"schema_id"`
Schema string `bson:"schema"`
}