-
Notifications
You must be signed in to change notification settings - Fork 77
/
helpers.go
58 lines (46 loc) 路 1.29 KB
/
helpers.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
package mongodb
import (
"context"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/utils"
"emperror.dev/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// https://stackoverflow.com/a/23650312/581476
func Paginate[T any](
ctx context.Context,
listQuery *utils.ListQuery,
collection *mongo.Collection,
filter interface{},
) (*utils.ListResult[T], error) {
if filter == nil {
filter = bson.D{}
}
count, err := collection.CountDocuments(ctx, filter)
if err != nil {
return nil, errors.WrapIf(err, "CountDocuments")
}
limit := int64(listQuery.GetLimit())
skip := int64(listQuery.GetOffset())
cursor, err := collection.Find(ctx, filter, &options.FindOptions{
Limit: &limit,
Skip: &skip,
})
if err != nil {
return nil, errors.WrapIf(err, "Find")
}
defer cursor.Close(ctx) // nolint: errcheck
products := make([]T, 0, listQuery.GetSize())
for cursor.Next(ctx) {
var prod T
if err := cursor.Decode(&prod); err != nil {
return nil, errors.WrapIf(err, "Find")
}
products = append(products, prod)
}
if err := cursor.Err(); err != nil {
return nil, errors.WrapIf(err, "cursor.Err")
}
return utils.NewListResult[T](products, listQuery.GetSize(), listQuery.GetPage(), count), nil
}