-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.go
More file actions
59 lines (48 loc) · 1.06 KB
/
storage.go
File metadata and controls
59 lines (48 loc) · 1.06 KB
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
package main
import (
"log"
"sync"
"time"
)
type UserCache struct {
createdAt time.Time
users Users
}
func (uc UserCache) Expired(now time.Time, expiry time.Duration) bool {
return uc.createdAt.Add(expiry).Before(now)
}
type Storage struct {
cache map[string]UserCache
cacheExpiry time.Duration
mu sync.Mutex
fetcher userGetter
}
func NewStorage(fetcher userGetter, cacheExpiry time.Duration) Storage {
return Storage{
cache: make(map[string]UserCache),
cacheExpiry: cacheExpiry,
fetcher: fetcher,
}
}
func (s Storage) Search(term string) (Users, error) {
s.mu.Lock()
defer s.mu.Unlock()
userCache, ok := s.cache[term]
if ok && !userCache.Expired(time.Now(), s.cacheExpiry) {
log.Printf("using cache for term %q", term)
return userCache.users, nil
}
log.Printf("fetching data for term %q", term)
users, err := s.fetcher.Search(term)
if err != nil {
return nil, err
}
if term != "" {
users = users.Refine(term)
}
s.cache[term] = UserCache{
createdAt: time.Now(),
users: users,
}
return users, nil
}