-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
69 lines (59 loc) · 1.55 KB
/
user.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
package service
import (
"context"
"fmt"
"strings"
"sync"
commonUtil "github.com/ffauzann/common/util"
"github.com/ffauzann/authentication/internal/constant"
"github.com/ffauzann/authentication/internal/model"
"github.com/ffauzann/authentication/internal/util"
)
func (s *service) IsUserExist(ctx context.Context, req *model.IsUserExistRequest) (res *model.IsUserExistResponse, err error) {
// Prepare concurrent
var wg sync.WaitGroup
chErr := make(chan error, 3)
chReason := make(chan string, 3)
fnIsExist := func(userIdType constant.UserIdType, userIdVal string) {
defer wg.Done()
isExist, err := s.repository.db.IsUserExist(ctx, userIdType, userIdVal)
if err != nil {
chErr <- err
return
}
if isExist {
chReason <- fmt.Sprintf("user with %s %s already exist", strings.Replace(string(userIdType), "_", " ", 1), userIdVal)
}
}
// Begin concurrent
if req.Email != "" {
wg.Add(1)
go fnIsExist(constant.UserIdTypeEmail, req.Email)
}
if req.PhoneNumber != "" {
wg.Add(1)
go fnIsExist(constant.UserIdTypePhoneNumber, req.PhoneNumber)
}
if req.Username != "" {
wg.Add(1)
go fnIsExist(constant.UserIdTypeUsername, req.Username)
}
wg.Wait()
// Begin non-blocking read channel
if err = commonUtil.ErrorFromChannel(chErr); err != nil {
util.Log().Error(err.Error())
return
}
// Read all channel values if any
close(chReason)
reasons := []string{}
for s := range chReason {
reasons = append(reasons, s)
}
// Format response
res = &model.IsUserExistResponse{
IsExist: len(reasons) > 0,
Reasons: reasons,
}
return
}