-
Notifications
You must be signed in to change notification settings - Fork 76
/
go-cache.go
69 lines (58 loc) · 1.49 KB
/
go-cache.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
// This is an exmaple of using go-cache as a long term cache solution for
// dataloader.
package main
import (
"context"
"fmt"
"time"
"github.com/nicksrandall/dataloader"
cache "github.com/patrickmn/go-cache"
)
// Cache implements the dataloader.Cache interface
type Cache struct {
c *cache.Cache
}
// Get gets a value from the cache
func (c *Cache) Get(key string) (dataloader.Thunk, bool) {
v, ok := c.c.Get(key)
if ok {
return v.(dataloader.Thunk), ok
}
return nil, ok
}
// Set sets a value in the cache
func (c *Cache) Set(key string, value dataloader.Thunk) {
c.c.Set(key, value, 0)
}
// Delete deletes and item in the cache
func (c *Cache) Delete(key string) bool {
if _, found := c.c.Get(key); found {
c.c.Delete(key)
return true
}
return false
}
// Clear clears the cache
func (c *Cache) Clear() {
c.c.Flush()
}
func main() {
// go-cache will automaticlly cleanup expired items on given diration
c := cache.New(15*time.Minute, 15*time.Minute)
cache := &Cache{c}
loader := dataloader.NewBatchedLoader(batchFunc, dataloader.WithCache(cache))
// immediately call the future function from loader
result, err := loader.Load(context.TODO(), "some key")()
if err != nil {
// handle error
}
fmt.Printf("identity: %s\n", result)
}
func batchFunc(_ context.Context, keys []string) []*dataloader.Result {
var results []*dataloader.Result
// do some pretend work to resolve keys
for _, key := range keys {
results = append(results, &dataloader.Result{key, nil})
}
return results
}