-
Notifications
You must be signed in to change notification settings - Fork 1
/
repo.go
48 lines (38 loc) · 1.47 KB
/
repo.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
package xmongo
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Repo[M any] struct {
collection *mongo.Collection
}
func NewRepo[M any](collection *mongo.Collection) (*Repo[M], error) {
return &Repo[M]{
collection: collection,
}, nil
}
func (r Repo[M]) Get(ctx context.Context, oid primitive.ObjectID) (*M, error) {
return r.FindOne(ctx, &bson.M{"_id": oid})
}
func (r Repo[M]) Find(ctx context.Context, filter interface{}, opts ...*options.FindOptions) ([]*M, error) {
return Find[M](ctx, r.collection, filter, opts...)
}
func (r Repo[M]) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) (*M, error) {
return FindOne[M](ctx, r.collection, filter, opts...)
}
func (r Repo[M]) InsertOne(ctx context.Context, doc M, opts ...*options.InsertOneOptions) (*mongo.InsertOneResult, error) {
return r.collection.InsertOne(ctx, doc, opts...)
}
func (r Repo[M]) InsertMany(ctx context.Context, docs []M, opts ...*options.InsertManyOptions) (*mongo.InsertManyResult, error) {
var inputs []interface{} = make([]interface{}, len(docs))
for i, d := range docs {
inputs[i] = d
}
return r.collection.InsertMany(ctx, inputs, opts...)
}
func (r Repo[M]) Aggregate(ctx context.Context, pipeline interface{}, opts ...*options.AggregateOptions) (*mongo.Cursor, error) {
return r.collection.Aggregate(ctx, pipeline, opts...)
}