Passed
Push — main ( f0dc1d...8ca1be )
by Yume
01:47 queued 29s
created

deck.*SQLRepository.GetByID   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
package deck
2
3
import (
4
	"github.com/memnix/memnix-rest/domain"
5
	"gorm.io/gorm"
6
)
7
8
// SQLRepository is the repository for the deck.
9
type SQLRepository struct {
10
	DBConn *gorm.DB
11
}
12
13
// Create creates a new deck.
14
func (r *SQLRepository) Create(deck *domain.Deck) error {
15
	return r.DBConn.Create(&deck).Error
16
}
17
18
// Update updates the deck with the given id.
19
func (r *SQLRepository) Update(deck *domain.Deck) error {
20
	return r.DBConn.Save(&deck).Error
21
}
22
23
// Delete deletes the deck with the given id.
24
func (r *SQLRepository) Delete(id uint) error {
25
	return r.DBConn.Delete(&domain.Deck{}, id).Error
26
}
27
28
// CreateFromUser creates a new deck from the given user.
29
func (r *SQLRepository) CreateFromUser(user domain.User, deck *domain.Deck) error {
30
	return r.DBConn.Model(&user).Association("OwnDecks").Append(deck)
31
}
32
33
// GetByID returns the deck with the given id.
34
func (r *SQLRepository) GetByID(id uint) (domain.Deck, error) {
35
	var deck domain.Deck
36
	err := r.DBConn.Preload("Learners").First(&deck, id).Error
37
	return deck, err
38
}
39
40
// GetByUser returns the decks of the given user.
41
func (r *SQLRepository) GetByUser(user domain.User) ([]domain.Deck, error) {
42
	var decks []domain.Deck
43
	err := r.DBConn.Model(&user).Association("OwnDecks").Find(&decks)
44
	return decks, err
45
}
46
47
// GetByLearner returns the decks of the given learner.
48
func (r *SQLRepository) GetByLearner(user domain.User) ([]domain.Deck, error) {
49
	var decks []domain.Deck
50
	err := r.DBConn.Model(&user).Association("Learning").Find(&decks)
51
	return decks, err
52
}
53
54
// GetPublic returns the public decks.
55
func (r *SQLRepository) GetPublic() ([]domain.Deck, error) {
56
	var decks []domain.Deck
57
	err := r.DBConn.Where("status = ?", domain.DeckStatusPublic).Find(&decks).Error
58
	return decks, err
59
}
60
61
// NewRepository returns a new repository.
62
func NewRepository(dbConn *gorm.DB) IRepository {
63
	return &SQLRepository{DBConn: dbConn}
64
}
65