Passed
Pull Request — main (#166)
by Yume
02:03
created

services/user/sqlRepository.go   A

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 31
dl 0
loc 60
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A user.*SQLRepository.GetByOauthID 0 4 1
A user.*SQLRepository.Update 0 2 1
A user.NewRepository 0 2 1
A user.*SQLRepository.GetByEmail 0 4 1
A user.*SQLRepository.Delete 0 2 1
A user.*SQLRepository.GetName 0 4 1
A user.*SQLRepository.Create 0 2 1
A user.*SQLRepository.GetByID 0 4 1
1
package user
2
3
import (
4
	"context"
5
6
	"github.com/memnix/memnix-rest/domain"
7
	"gorm.io/gorm"
8
)
9
10
// SQLRepository is the repository for the user.
11
type SQLRepository struct {
12
	DBConn *gorm.DB // DBConn is the database connection.
13
}
14
15
// NewRepository returns a new repository.
16
func NewRepository(dbConn *gorm.DB) IRepository {
17
	return &SQLRepository{DBConn: dbConn}
18
}
19
20
// GetName returns the name of the user.
21
func (r *SQLRepository) GetName(ctx context.Context, id uint) string {
22
	var user domain.User
23
	r.DBConn.WithContext(ctx).First(&user, id)
24
	return user.Username
25
}
26
27
// GetByID returns the user with the given id.
28
func (r *SQLRepository) GetByID(ctx context.Context, id uint) (domain.User, error) {
29
	var user domain.User
30
	err := r.DBConn.WithContext(ctx).First(&user, id).Error
31
	return user, err
32
}
33
34
// GetByEmail returns the user with the given email.
35
func (r *SQLRepository) GetByEmail(ctx context.Context, email string) (domain.User, error) {
36
	var user domain.User
37
	err := r.DBConn.WithContext(ctx).Where("email = ?", email).First(&user).Error
38
	return user, err
39
}
40
41
// Create creates a new user.
42
func (r *SQLRepository) Create(ctx context.Context, user *domain.User) error {
43
	return r.DBConn.WithContext(ctx).Create(&user).Error
44
}
45
46
// Update updates the user with the given id.
47
func (r *SQLRepository) Update(ctx context.Context, user *domain.User) error {
48
	return r.DBConn.WithContext(ctx).Save(&user).Error
49
}
50
51
// Delete deletes the user with the given id.
52
func (r *SQLRepository) Delete(ctx context.Context, id uint) error {
53
	return r.DBConn.WithContext(ctx).Delete(&domain.User{}, id).Error
54
}
55
56
// GetByOauthID returns the user with the given oauth id.
57
func (r *SQLRepository) GetByOauthID(ctx context.Context, id string) (domain.User, error) {
58
	var user domain.User
59
	err := r.DBConn.WithContext(ctx).Where("oauth_id = ?", id).First(&user).Error
60
	return user, err
61
}
62