-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
52 lines (41 loc) · 1.66 KB
/
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
package users
import (
"context"
"github.com/sercanakmaz/go-boilerplate-v3/pkg/ddd"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type IUserRepository interface {
FindOneById(ctx context.Context, id primitive.ObjectID) (*User, error)
FindOneByUsername(ctx context.Context, username string) (*User, error)
Add(ctx context.Context, user *User) error
Update(ctx context.Context, user *User) error
}
const _collectionName = "Users"
type userRepository struct {
db *mongo.Database
eventDispatcher ddd.IEventDispatcher
}
func newUserRepository(db *mongo.Database, eventDispatcher ddd.IEventDispatcher) IUserRepository {
return &userRepository{db: db, eventDispatcher: eventDispatcher}
}
func (repository userRepository) FindOneById(ctx context.Context, id primitive.ObjectID) (*User, error) {
var user *User
err := repository.db.Collection(_collectionName).FindOne(ctx, bson.M{"_id": id}).Decode(&user)
return user, err
}
func (repository userRepository) FindOneByUsername(ctx context.Context, username string) (*User, error) {
var user *User
err := repository.db.Collection(_collectionName).FindOne(ctx, bson.M{"username": username}).Decode(&user)
return user, err
}
func (repository userRepository) Add(ctx context.Context, user *User) error {
_, err := repository.db.Collection(_collectionName).InsertOne(ctx, &user, options.InsertOne())
return err
}
func (repository userRepository) Update(ctx context.Context, user *User) error {
_, err := repository.db.Collection(_collectionName).ReplaceOne(ctx, bson.M{"_id": user.Id}, &user)
return err
}