/
user_repository.go
127 lines (100 loc) · 2.56 KB
/
user_repository.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
package repository
import (
"context"
"fmt"
"github.com/namcchan/go-chatting/database"
"github.com/namcchan/go-chatting/internal/domain"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type userRepository struct {
ctx context.Context
userCollection *mongo.Collection
}
func NewUserRepository(ctx context.Context) domain.UserRepository {
return &userRepository{
ctx: ctx,
userCollection: database.GetCollection(domain.CollectionUser),
}
}
func (ur *userRepository) Find(filter bson.M) ([]domain.User, error) {
var results []domain.User
cur, err := ur.userCollection.Find(ur.ctx, filter)
if err != nil {
return nil, fmt.Errorf("failed to find documents: %v", err)
}
defer cur.Close(ur.ctx)
for cur.Next(ur.ctx) {
var user domain.User
err := cur.Decode(&user)
if err != nil {
return nil, err
}
results = append(results, user)
}
if err := cur.Err(); err != nil {
return nil, err
}
return results, nil
}
func (ur *userRepository) FindWithPagination(filter bson.M, limit int64, page int64) ([]domain.User, error) {
skip := (page - 1) * limit
findOptions := options.Find()
findOptions.SetSkip(skip)
findOptions.SetLimit(limit)
cur, err := ur.userCollection.Find(ur.ctx, filter, findOptions)
if err != nil {
return nil, err
}
defer cur.Close(ur.ctx)
var results []domain.User
for cur.Next(ur.ctx) {
var document domain.User
err := cur.Decode(&document)
if err != nil {
return nil, err
}
results = append(results, document)
}
if err := cur.Err(); err != nil {
return nil, err
}
return results, nil
}
func (ur *userRepository) Delete(filter bson.M) error {
_, err := ur.userCollection.DeleteMany(ur.ctx, filter)
if err != nil {
return err
}
return nil
}
func (ur *userRepository) Update(filter bson.M, update bson.M) error {
_, err := ur.userCollection.UpdateMany(ur.ctx, filter, update)
if err != nil {
return err
}
return nil
}
func (ur *userRepository) Create(document *domain.User) error {
_, err := ur.userCollection.InsertOne(ur.ctx, document)
if err != nil {
return err
}
return nil
}
func (ur *userRepository) FindOne(filter bson.M, projection bson.M) (*domain.User, error) {
var user *domain.User
opts := options.FindOne()
if projection != nil {
opts.SetProjection(projection)
}
err := ur.userCollection.FindOne(ur.ctx, filter, opts).Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
return user, nil // Return empty user if no document found
}
return user, nil
}
return user, nil
}