forked from kkdai/youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecipher_operations_cache.go
More file actions
51 lines (41 loc) · 1.36 KB
/
decipher_operations_cache.go
File metadata and controls
51 lines (41 loc) · 1.36 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
package youtube
import "time"
var (
_ DecipherOperationsCache = NewSimpleCache()
)
const defaultCacheExpiration = time.Minute * time.Duration(5)
type DecipherOperationsCache interface {
Get(videoID string) []DecipherOperation
Set(video string, operations []DecipherOperation)
}
type SimpleCache struct {
videoID string
expiredAt time.Time
operations []DecipherOperation
}
func NewSimpleCache() *SimpleCache {
return &SimpleCache{}
}
// Get : get cache when it has same video id and not expired
func (s SimpleCache) Get(videoID string) []DecipherOperation {
return s.GetCacheBefore(videoID, time.Now())
}
// GetCacheBefore : can pass time for testing
func (s SimpleCache) GetCacheBefore(videoID string, time time.Time) []DecipherOperation {
if videoID == s.videoID && s.expiredAt.After(time) {
operations := make([]DecipherOperation, len(s.operations))
copy(operations, s.operations)
return operations
}
return nil
}
// Set : set cache with default expiration
func (s *SimpleCache) Set(videoID string, operations []DecipherOperation) {
s.setWithExpiredTime(videoID, operations, time.Now().Add(defaultCacheExpiration))
}
func (s *SimpleCache) setWithExpiredTime(videoID string, operations []DecipherOperation, time time.Time) {
s.videoID = videoID
s.operations = make([]DecipherOperation, len(operations))
copy(s.operations, operations)
s.expiredAt = time
}