-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
102 lines (96 loc) · 2.38 KB
/
service.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
package service
import (
"context"
"database/sql"
. "go-service/internal/user/domain"
. "go-service/internal/user/port"
)
type UserService interface {
Load(ctx context.Context, id string) (*User, error)
Create(ctx context.Context, user *User) (int64, error)
Update(ctx context.Context, user *User) (int64, error)
Patch(ctx context.Context, user map[string]interface{}) (int64, error)
Delete(ctx context.Context, id string) (int64, error)
Search(ctx context.Context, filter *UserFilter) ([]User, int64, error)
}
func NewUserService(db *sql.DB, repository UserRepository) UserService {
return &UserUseCase{db: db, repository: repository}
}
type UserUseCase struct {
db *sql.DB
repository UserRepository
}
func (s *UserUseCase) Load(ctx context.Context, id string) (*User, error) {
return s.repository.Load(ctx, id)
}
func (s *UserUseCase) Create(ctx context.Context, user *User) (int64, error) {
tx, err := s.db.Begin()
if err != nil {
return -1, nil
}
ctx = context.WithValue(ctx, "tx", tx)
res, err := s.repository.Create(ctx, user)
if err != nil {
er := tx.Rollback()
if er != nil {
return -1, er
}
return -1, err
}
err = tx.Commit()
return res, err
}
func (s *UserUseCase) Update(ctx context.Context, user *User) (int64, error) {
tx, err := s.db.Begin()
if err != nil {
return -1, nil
}
ctx = context.WithValue(ctx, "tx", tx)
res, err := s.repository.Update(ctx, user)
if err != nil {
er := tx.Rollback()
if er != nil {
return -1, er
}
return -1, err
}
err = tx.Commit()
return res, err
}
func (s *UserUseCase) Patch(ctx context.Context, user map[string]interface{}) (int64, error) {
tx, err := s.db.Begin()
if err != nil {
return -1, nil
}
ctx = context.WithValue(ctx, "tx", tx)
res, err := s.repository.Patch(ctx, user)
if err != nil {
er := tx.Rollback()
if er != nil {
return -1, er
}
return -1, err
}
err = tx.Commit()
return res, err
}
func (s *UserUseCase) Delete(ctx context.Context, id string) (int64, error) {
tx, err := s.db.Begin()
if err != nil {
return -1, nil
}
ctx = context.WithValue(ctx, "tx", tx)
res, err := s.repository.Delete(ctx, id)
if err != nil {
er := tx.Rollback()
if er != nil {
return -1, er
}
return -1, err
}
err = tx.Commit()
return res, err
}
func (s *UserUseCase) Search(ctx context.Context, filter *UserFilter) ([]User, int64, error) {
return s.repository.Search(ctx, filter)
}