/
mongo_generic.go
129 lines (92 loc) · 2.38 KB
/
mongo_generic.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package database
import (
"context"
"encoding/json"
specification "github.com/behrouz-rfa/mongo-specification/pkg/infrastructure/database/specefication"
"github.com/fatih/structs"
"github.com/gertd/go-pluralize"
"github.com/iancoleman/strcase"
"go.mongodb.org/mongo-driver/mongo"
"log"
)
var pluralizer *pluralize.Client
func Init() {
pluralizer = pluralize.NewClient()
}
func collectionName[T any](s T) string {
name := structs.Name(s)
name = strcase.ToLowerCamel(name)
name = pluralizer.Plural(name)
return name
}
type FindByParams[Q, T any] struct {
Spec specification.Set
Collection *mongo.Collection
ToModel func(Q) *T
}
func FindOneBy[Q, T any](ctx context.Context, params *FindByParams[Q, T]) (*T, error) {
var results []Q
params.Spec.WithContext(ctx).Limit(1)
cursor, err := params.Collection.Aggregate(ctx, params.Spec.Query())
if err != nil {
return nil, err
}
err = cursor.All(ctx, &results)
if err != nil {
return nil, err
}
if len(results) < 1 {
return nil, nil
}
return params.ToModel(results[0]), nil
}
func FindBy[Q, T any](ctx context.Context, params *FindByParams[Q, T]) ([]*T, error) {
var results []*T
params.Spec.WithContext(ctx)
cursor, err := params.Collection.Aggregate(ctx, params.Spec.Query(), DiskAggregationOption)
if err != nil {
return nil, err
}
for cursor.Next(ctx) {
var result Q
err = cursor.Decode(&result)
if err != nil {
return nil, err
}
results = append(results, params.ToModel(result))
}
return results, nil
}
func LogList(ctx context.Context, m *mongo.Collection, spec specification.Set) {
obj := make([]map[string]interface{}, 0)
cursor, err := m.Aggregate(ctx, spec.Query(), DiskAggregationOption)
if err != nil {
log.Println(err)
}
for cursor.Next(ctx) {
var result map[string]interface{}
err = cursor.Decode(&result)
if err != nil {
log.Println(err)
}
obj = append(obj, result)
}
res, _ := json.MarshalIndent(obj[0], "", " ")
log.Println(string(res))
}
func LogObject(ctx context.Context, m *mongo.Collection, spec specification.Set) {
obj := make([]map[string]interface{}, 0)
cursor, err := m.Aggregate(ctx, spec.Query(), DiskAggregationOption)
if err != nil {
log.Println(err)
}
err = cursor.All(ctx, &obj)
if err != nil {
log.Println(err)
}
if len(obj) < 1 {
return
}
res, _ := json.MarshalIndent(obj[0], "", " ")
log.Println(string(res))
}