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

deck.*SQLRepository.Create   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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