-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddlewares.go
58 lines (52 loc) · 1.14 KB
/
middlewares.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
package tinydb
import (
"encoding/json"
)
// MiddlewareCaching is a middleware for caching data.
type MiddlewareCaching struct {
storage Storage
cache []byte
count int
size int
}
// CachingMiddleware Create a new CachingMiddleware instance.
func CachingMiddleware(storage Storage, size int) *MiddlewareCaching {
return &MiddlewareCaching{storage: storage, size: size}
}
// Read data from MiddlewareCaching cache.
func (mv *MiddlewareCaching) Read(data any) error {
if mv.cache == nil {
return mv.storage.Read(data)
}
return json.Unmarshal(mv.cache, &data)
}
// Write data to MiddlewareCaching cache.
func (mv *MiddlewareCaching) Write(data any) error {
b, err := json.Marshal(data)
if err != nil {
return err
}
mv.cache = b
mv.count++
if mv.count >= mv.size {
err := mv.Read(data)
if err != nil {
return err
}
return mv.storage.Write(data)
}
return nil
}
// Close the MemoryStorage instance.
func (mv *MiddlewareCaching) Close() error {
var data = make(map[string]interface{})
err := mv.Read(data)
if err != nil {
return err
}
err = mv.storage.Write(data)
if err != nil {
return err
}
return mv.storage.Close()
}