-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcache.go
51 lines (40 loc) · 1.42 KB
/
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
package dataloader
import (
"context"
)
type CacheKeyFunc[K any, C comparable] func(ctx context.Context, key K) (C, error)
type CacheMap[C comparable, V any] interface {
Get(ctx context.Context, key C) (V, error)
Set(ctx context.Context, key C, val V) error
Delete(ctx context.Context, key C) error
Clear(ctx context.Context) error
}
type NoCache[C comparable, V any] struct{}
func NewNoCache[C comparable, V any]() *NoCache[C, V] { return &NoCache[C, V]{} }
func (c *NoCache[C, V]) Get(ctx context.Context, key C) (V, error) { return *new(V), nil }
func (c *NoCache[C, V]) Set(ctx context.Context, key C, val V) error { return nil }
func (c *NoCache[C, V]) Delete(ctx context.Context, key C) error { return nil }
func (c *NoCache[C, V]) Clear(ctx context.Context) error { return nil }
type InMemoryCache[C comparable, V any] struct {
items map[C]V
}
func NewInMemoryCache[C comparable, V any]() *InMemoryCache[C, V] {
return &InMemoryCache[C, V]{
items: make(map[C]V),
}
}
func (c *InMemoryCache[C, V]) Get(ctx context.Context, key C) (V, error) {
return c.items[key], nil
}
func (c *InMemoryCache[C, V]) Set(ctx context.Context, key C, val V) error {
c.items[key] = val
return nil
}
func (c *InMemoryCache[C, V]) Delete(ctx context.Context, key C) error {
delete(c.items, key)
return nil
}
func (c *InMemoryCache[C, V]) Clear(ctx context.Context) error {
c.items = make(map[C]V)
return nil
}