-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache.go
More file actions
83 lines (71 loc) · 2.01 KB
/
cache.go
File metadata and controls
83 lines (71 loc) · 2.01 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package gsheets
import (
"context"
"errors"
"strings"
"sync"
sheets "google.golang.org/api/sheets/v4"
)
type contextKey string
const cacheKey contextKey = "cache-key"
type gsCache struct {
cache map[string]interface{}
m sync.RWMutex
}
// WithCache returns a context with gsheets cache.
// If you want to use the cache, initialize the context.
func WithCache(ctx context.Context) context.Context {
return context.WithValue(ctx, cacheKey, &gsCache{
cache: map[string]interface{}{},
})
}
func setCache(ctx context.Context, resp interface{}, srvName serviceName, keys ...string) error {
v := ctx.Value(cacheKey)
c, ok := v.(*gsCache)
if !ok {
return errors.New("the context has not been initialized for gsheets package")
}
k := strings.Join(append([]string{string(srvName)}, keys...), "-")
c.m.Lock()
defer c.m.Unlock()
c.cache[k] = resp
return nil
}
func getCache(ctx context.Context, srvName serviceName, keys ...string) (interface{}, error) {
v := ctx.Value(cacheKey)
c, ok := v.(*gsCache)
if !ok {
return nil, errors.New("the context has not been initialized for gsheets package")
}
k := strings.Join(append([]string{string(srvName)}, keys...), "-")
c.m.RLock()
defer c.m.RUnlock()
return c.cache[k], nil
}
type serviceName string
const (
srvNameSpreadsheets = "Spreadsheets"
srvNameSpreadsheetsValues = "SpreadsheetsValues"
)
func getSpreadsheetsCache(ctx context.Context, spreadsheetID string) (*sheets.Spreadsheet, error) {
v, err := getCache(ctx, srvNameSpreadsheets, spreadsheetID)
if err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
s, _ := v.(*sheets.Spreadsheet)
return s, nil
}
func getSpreadsheetsValuesCache(ctx context.Context, spreadsheetID, sheetName string) (*sheets.ValueRange, error) {
v, err := getCache(ctx, srvNameSpreadsheetsValues, spreadsheetID)
if err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
s, _ := v.(*sheets.ValueRange)
return s, nil
}