-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.go
112 lines (96 loc) · 2.19 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
103
104
105
106
107
108
109
110
111
112
package railroad
import (
"fmt"
"strings"
)
type UserService struct {
db map[string]UserRegistrationRequest
}
func NewUserService() UserService {
return UserService{
db: map[string]UserRegistrationRequest{},
}
}
func (us *UserService) Register(req UserRegistrationRequest) bool {
return Result{State: req}.
Apply(us.ValidateRequest).
Apply(us.CheckUserExists).
Apply(us.SaveUserInDatabase).
Success
}
func (us *UserService) ValidateRequest(res Result) Result {
req, ok := res.State.(UserRegistrationRequest)
if !ok {
return Result{
State: res.State,
Success: false,
Failure: true,
Err: fmt.Errorf("state passed as parameter was not of type UserRegistrationRequest"),
}
}
username := req.Username
email := req.Email
if len(username) > 10 {
return Result{
State: nil,
Success: false,
Failure: true,
Err: fmt.Errorf("Username %v has a length of %v which is less than 10", username, len(username)),
}
}
if !strings.Contains(email, "@") {
return Result{
State: nil,
Success: false,
Failure: true,
Err: fmt.Errorf("Email %v must contain an @ sign ", email),
}
}
return Result{
State: req,
Success: true,
Failure: false,
}
}
func (us *UserService) CheckUserExists(res Result) Result {
req, ok := res.State.(UserRegistrationRequest)
if !ok {
return Result{
State: res.State,
Success: false,
Failure: true,
Err: fmt.Errorf("state passed as parameter was not of type UserRegistrationRequest"),
}
}
username := strings.ToLower(req.Username)
if strings.HasPrefix(username, "c") {
return Result{
State: nil,
Success: false,
Failure: true,
Err: fmt.Errorf("User with username '%v' already exists", req.Username),
}
}
return Result{
State: req,
Success: true,
Failure: false,
}
}
func (us *UserService) SaveUserInDatabase(res Result) Result {
req, ok := res.State.(UserRegistrationRequest)
if !ok {
return Result{
State: res.State,
Success: false,
Failure: true,
Err: fmt.Errorf("state passed as parameter was not of type UserRegistrationRequest"),
}
}
us.db[req.Username] = req
return Result{
State: req,
Success: true,
Failure: false,
}
}