-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathservice.go
92 lines (75 loc) · 1.78 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
package main
import (
"log"
"time"
)
type Service interface {
getLinkForShortID(shortID string) (*Link, error)
incrementGlobalCounter() uint
incrementLinkCounter(link *Link)
newLink(URL string) *Link
close()
}
type ServiceImpl struct {
linkRepo LinkRepository
counterRepo CounterRepository
}
func (s *ServiceImpl) newLink(URL string) *Link {
var timenow = time.Now().UTC()
var counter = s.incrementGlobalCounter()
var shortID = baseconv.Encode(counter)
link := Link{
ID: URL + "-" + shortID,
URL: URL,
Clicks: 0,
ShortID: shortID,
ShortIDInt: counter,
CreatedAt: &timenow,
UpdatedAt: &timenow,
}
err := s.linkRepo.InsertLink(link)
if err != nil {
log.Fatal("Error inserting new link ", err)
}
return &link
}
func (s *ServiceImpl) getLinkForShortID(shortID string) (*Link, error) {
if len(shortID) > 10 {
return nil, errInvalidLink
}
shortIDInt := baseconv.Decode(shortID)
link, err := s.linkRepo.FindLinkByShortIdInt(shortIDInt)
return link, err
}
func (s *ServiceImpl) incrementLinkCounter(link *Link) {
var timenow = time.Now().UTC()
link.Clicks++
link.UpdatedAt = &timenow
err := s.linkRepo.UpdateLink(*link)
if err != nil {
log.Fatal("Error incrementing counter for link", link, err)
}
}
func (s *ServiceImpl) incrementGlobalCounter() uint {
var timenow = time.Now().UTC()
counter, err := s.counterRepo.FindCounterById("1")
if counter == nil {
counter = &Counter{
ID: "1",
Count: 0,
CreatedAt: &timenow,
StatType: "counter",
}
}
counter.Count++
counter.UpdatedAt = &timenow
err = s.counterRepo.UpsertCounter(*counter)
if err != nil {
log.Fatal("Failed updating global counter ", err)
}
return counter.Count
}
func (s *ServiceImpl) close() {
s.linkRepo.close()
s.counterRepo.close()
}