-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
81 lines (71 loc) · 2.59 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
package user
import (
"context"
"github.com/tvitcom/local-adverts/internal/entity"
"github.com/tvitcom/local-adverts/pkg/dbcontext"
"github.com/tvitcom/local-adverts/pkg/log"
)
// repository persists users in database
type repository struct {
db *dbcontext.DB
logger log.Logger
}
// Repository encapsulates the logic to access users from the data source.
type Repository interface {
// Get returns the user with the specified user ID.
Get(ctx context.Context, id string) (entity.User, error)
// Count returns the number of users.
Count(ctx context.Context) (int, error)
// Query returns the list of users with the given offset and limit.
Query(ctx context.Context, offset, limit int) ([]entity.User, error)
// Create saves a new user in the storage.
Create(ctx context.Context, user entity.User) error
// Update updates the user with given ID in the storage.
Update(ctx context.Context, user entity.User) error
// Delete removes the user with given ID from the storage.
Delete(ctx context.Context, id string) error
}
// NewRepository creates a new user repository
func NewRepository(db *dbcontext.DB, logger log.Logger) Repository {
return repository{db, logger}
}
// Get reads the user with the specified ID from the database.
func (r repository) Get(ctx context.Context, id string) (entity.User, error) {
var user entity.User
err := r.db.With(ctx).Select().Model(id, &user)
return user, err
}
// Create saves a new user record in the database.
// It returns the ID of the newly inserted user record.
func (r repository) Create(ctx context.Context, user entity.User) error {
return r.db.With(ctx).Model(&user).Insert()
}
// Update saves the changes to an user in the database.
func (r repository) Update(ctx context.Context, user entity.User) error {
return r.db.With(ctx).Model(&user).Update()
}
// Delete deletes an user with the specified ID from the database.
func (r repository) Delete(ctx context.Context, id string) error {
user, err := r.Get(ctx, id)
if err != nil {
return err
}
return r.db.With(ctx).Model(&user).Delete()
}
// Count returns the number of the user records in the database.
func (r repository) Count(ctx context.Context) (int, error) {
var count int
err := r.db.With(ctx).Select("COUNT(*)").From("user").Row(&count)
return count, err
}
// Query retrieves the user records with the specified offset and limit from the database.
func (r repository) Query(ctx context.Context, offset, limit int) ([]entity.User, error) {
var users []entity.User
err := r.db.With(ctx).
Select().
OrderBy("id").
Offset(int64(offset)).
Limit(int64(limit)).
All(&users)
return users, err
}