-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_repository.go
64 lines (51 loc) · 1.03 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
package main
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
type UserRepo struct {
coll *mongo.Collection
}
func NewUserRepo(db *mongo.Database) *UserRepo {
return &UserRepo{
db.Collection("users"),
}
}
func (r *UserRepo) Find(UserID int64) *User {
res := r.coll.FindOne(context.TODO(), bson.D{
{Key: "user_id", Value: UserID},
})
if res.Err() != nil {
return nil
}
var User User
res.Decode(&User)
return &User
}
func (r *UserRepo) FindOrInsert(UserID int64) (bool, *User) {
var (
user = r.Find(UserID)
insrt = false
)
if user == nil {
res, err := r.coll.InsertOne(context.TODO(), User{
UserID: UserID,
})
CheckIfError(err)
insrt = true
if oid, ok := res.InsertedID.(primitive.ObjectID); ok {
user = &User{ID: &oid, UserID: UserID}
}
}
return insrt, user
}
func (r *UserRepo) Update(user *User) {
_, err := r.coll.ReplaceOne(
context.TODO(),
bson.M{"_id": user.ID},
user,
)
CheckIfError(err)
}