-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_repository.go
52 lines (46 loc) · 1.37 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
package orm
import (
"context"
"errors"
"github.com/sajjad1993/todo/pkg/errs"
"github.com/sajjad1993/todo/services/user/domain/user"
"gorm.io/gorm"
)
type UserRepository struct {
db *gorm.DB
}
func NewUserRepository(db *gorm.DB) user.Repository {
return &UserRepository{db: db}
}
func (r *UserRepository) GetById(ctx context.Context, id uint) (*user.User, error) {
model := new(User)
err := r.db.WithContext(ctx).Where("id = ?", id).First(model).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errs.NewNotFoundError(err.Error())
}
return nil, errs.NewInternalError(err.Error())
}
return model.toEntity(), nil
}
func (r *UserRepository) GetByEmail(ctx context.Context, email string) (*user.User, error) {
model := new(User)
err := r.db.WithContext(ctx).Where("email = ?", email).First(model).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errs.NewNotFoundError(err.Error())
}
return nil, errs.NewInternalError(err.Error())
}
return model.toEntity(), nil
}
func (r *UserRepository) Create(ctx context.Context, userEnt *user.User) error {
model := new(User).fromEntity(userEnt)
if err := r.db.WithContext(ctx).Create(model).Error; err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
return errs.NewDuplicateEntity(err.Error())
}
return errs.NewInternalError(err.Error())
}
return nil
}