-
Notifications
You must be signed in to change notification settings - Fork 2
/
mongotest.go
94 lines (83 loc) · 2.58 KB
/
mongotest.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
89
90
91
92
93
94
package mongotest
import (
"context"
"github.com/tkuchiki/parsetime"
"go.mongodb.org/mongo-driver/bson"
)
// Try connecting to MongoDB server.
func Try() error {
if err := validateConfig(); err != nil {
return err
}
ctx, client, cancel, err := connect(context.Background())
if err != nil {
return err
}
defer cancel()
return client.Ping(ctx, nil)
}
// CountWithContext returns document count in collection that has given name.
// This function uses given context.
func CountWithContext(ctx context.Context, collectionName string) (int64, error) {
ctx, coll, cancel, err := connectCollection(ctx, collectionName)
if err != nil {
return 0, err
}
defer cancel()
n, err := coll.CountDocuments(ctx, bson.M{})
if err != nil {
return 0, err
}
return n, nil
}
// CountIntWithContext returns document count as int in collection that has given name.
// This function uses given context.
func CountIntWithContext(ctx context.Context, collectionName string) (int, error) {
n, err := CountWithContext(ctx, collectionName)
return int(n), err
}
// Count returns document count in collection that has given name.
func Count(collectionName string) (int64, error) {
return CountWithContext(context.Background(), collectionName)
}
// CountInt returns document count as int in collection that has given name.
func CountInt(collectionName string) (int, error) {
return CountIntWithContext(context.Background(), collectionName)
}
// FindWithContext document that has given id in given named collection.
// This function uses given context.
func FindWithContext(ctx context.Context, collectionName string, id interface{}) (map[string]interface{}, error) {
ctx, coll, cancel, err := connectCollection(ctx, collectionName)
if err != nil {
return nil, err
}
defer cancel()
var doc bson.M
err = coll.FindOne(ctx, bson.M{"_id": id}).Decode(&doc)
return doc, err
}
// Find document that has given id in given named collection.
func Find(collectionName string, id interface{}) (map[string]interface{}, error) {
return FindWithContext(context.Background(), collectionName, id)
}
// SimpleConvertTime provides simple PreInsertFunc for converting string time to time.Time.
func SimpleConvertTime(collectionName, fieldName string) PreInsertFunc {
return func(collName string, value DocData) (DocData, error) {
if collName == collectionName {
sv, ok := value.StringValue(fieldName)
if !ok {
return value, nil
}
p, err := parsetime.NewParseTime()
if err != nil {
return nil, err
}
t, err := p.Parse(sv)
if err != nil {
return nil, err
}
value[fieldName] = t
}
return value, nil
}
}