forked from metafates/mangal
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
53 lines (44 loc) 路 1 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
52
53
package mangadex
import (
"github.com/belphemur/mangal/filesystem"
"github.com/belphemur/mangal/where"
"github.com/metafates/gache"
"github.com/samber/mo"
"path/filepath"
"time"
)
type cacher[T any] struct {
internal *gache.Cache[map[string]T]
}
func newCacher[T any](name string) *cacher[T] {
return &cacher[T]{
internal: gache.New[map[string]T](
&gache.Options{
Path: filepath.Join(where.Cache(), name+".json"),
Lifetime: time.Hour * 24,
FileSystem: &filesystem.GacheFs{},
},
),
}
}
func (c *cacher[T]) Get(key string) mo.Option[T] {
cached, expired, err := c.internal.Get()
if err != nil || expired || cached == nil {
return mo.None[T]()
}
if value, ok := cached[key]; ok {
return mo.Some[T](value)
}
return mo.None[T]()
}
func (c *cacher[T]) Set(key string, value T) error {
cached, expired, err := c.internal.Get()
if err != nil {
return err
}
if expired || cached == nil {
cached = map[string]T{}
}
cached[key] = value
return c.internal.Set(cached)
}