-
Notifications
You must be signed in to change notification settings - Fork 0
/
readWriter.go
99 lines (85 loc) · 2.4 KB
/
readWriter.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
package userRW
import (
"context"
"fmt"
"github.com/spf13/viper"
"go.mongodb.org/mongo-driver/bson"
"log"
"time"
"github.com/saeidraei/go-jwt-auth/domain"
"github.com/saeidraei/go-jwt-auth/uc"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type rw struct {
client *mongo.Client
collection *mongo.Collection
}
func New() uc.UserRW {
client, err := mongo.NewClient(options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s:%s",
viper.GetString("mongo.user"),
viper.GetString("mongo.password"),
viper.GetString("mongo.host"),
viper.GetString("mongo.port"))))
if err != nil {
log.Println(err)
panic(err.Error())
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
collection := client.Database("clean").Collection("users")
return rw{
client: client,
collection: collection,
}
}
func (rw rw) Create(username, email, password string) (*domain.User, error) {
if _, err := rw.GetByEmail(email); err == nil {
return nil, uc.ErrAlreadyInUse
}
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
_, err := rw.collection.InsertOne(ctx, bson.M{"Name": username, "Email": email, "Password": password})
if err != nil {
panic(err)
}
return rw.GetByEmail(email)
}
func (rw rw) GetByName(userName string) (*domain.User, error) {
var user domain.User
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
res := rw.collection.FindOne(ctx, bson.M{"Name": userName})
err := res.Decode(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func (rw rw) GetByEmail(email string) (*domain.User, error) {
var user domain.User
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
res := rw.collection.FindOne(ctx, bson.M{"Email": email})
err := res.Decode(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func (rw rw) GetByEmailAndPassword(email, password string) (*domain.User, error) {
var user domain.User
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
res := rw.collection.FindOne(ctx, bson.M{"Email": email, "Password": password})
err := res.Decode(&user)
if err != nil {
return nil, err
}
return &user, nil
}
func (rw rw) Save(user domain.User) error {
//if user, _ := rw.GetByName(user.Name); user == nil {
// return uc.ErrNotFound
//}
//
//user.UpdatedAt = time.Now()
//rw.store.Store(user.Name, user)
return nil
}