-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrepository.go
111 lines (90 loc) · 2.39 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package meta_gin
import (
"gorm.io/gorm"
)
type SortOrder string
const (
Asc SortOrder = "ASC"
Desc SortOrder = "DESC"
)
type PaginatedResponse struct {
TotalCount int64 `json:"total_count"`
TotalPages int `json:"total_pages"`
Page int `json:"page"`
PageSize int `json:"page_size"`
Data interface{} `json:"data"`
}
type Repository[M any] struct {
DB *gorm.DB
}
func NewRepository[M any](db *gorm.DB) *Repository[M] {
return &Repository[M]{DB: db}
}
func (r *Repository[M]) Create(model M) (M, error) {
err := r.DB.Create(&model).Error
return model, err
}
func (r *Repository[M]) FindOrCreate(model M) error {
return r.DB.FirstOrCreate(&model).Error
}
func (r *Repository[M]) FindByID(id string) (M, error) {
var model M
err := r.DB.First(&model, id).Error
return model, err
}
func (r *Repository[M]) Update(model M) error {
return r.DB.Save(&model).Error
}
func (r *Repository[M]) Delete(model M) error {
return r.DB.Delete(&model).Error
}
func (r *Repository[M]) DeleteByID(id string) error {
return r.DB.Delete(new(M), id).Error
}
type QueryOption func(db *gorm.DB) *gorm.DB
func WithCondition(condition string, args ...interface{}) QueryOption {
return func(db *gorm.DB) *gorm.DB {
return db.Where(condition, args...)
}
}
func WithPagination(page, pageSize int) QueryOption {
return func(db *gorm.DB) *gorm.DB {
return db.Offset((page - 1) * pageSize).Limit(pageSize)
}
}
func WithOrder(order string) QueryOption {
return func(db *gorm.DB) *gorm.DB {
return db.Order(order)
}
}
func WithSort(field string, order SortOrder) QueryOption {
return func(db *gorm.DB) *gorm.DB {
return db.Order(field + " " + string(order))
}
}
func WithCount(count *int64) QueryOption {
return func(db *gorm.DB) *gorm.DB {
return db.Count(count)
}
}
func (r *Repository[M]) Find(options ...QueryOption) ([]M, error) {
var models []M
db := r.DB.Model(new(M))
for _, option := range options {
db = option(db)
}
err := db.Find(&models).Error
return models, err
}
func (r *Repository[M]) FindOne(options ...QueryOption) (M, error) {
var model M
db := r.DB.Model(new(M))
for _, option := range options {
db = option(db)
}
err := db.First(&model).Error
return model, err
}
func (r *Repository[M]) UpdateWithCondition(model M, condition string, args ...interface{}) error {
return r.DB.Model(&model).Where(condition, args...).Updates(&model).Error
}