-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_event_hander.go
More file actions
49 lines (43 loc) · 1.16 KB
/
cache_event_hander.go
File metadata and controls
49 lines (43 loc) · 1.16 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
package mongo_watcher
import (
"context"
"github.com/techpro-studio/gocache"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"log"
)
type CacheEventHandler[T any, M MongoSchema[T]] struct {
cache gocache.TypedCache[T]
preheat bool
}
func NewCacheEventHandler[T any, M MongoSchema[T]](cache gocache.TypedCache[T], preheat bool) *CacheEventHandler[T, M] {
return &CacheEventHandler[T, M]{cache: cache, preheat: preheat}
}
func (c *CacheEventHandler[T, M]) Setup(ctx context.Context, collection *mongo.Collection) {
if !c.preheat {
return
}
find, err := collection.Find(ctx, bson.M{})
if err != nil {
return
}
var all []M
err = find.All(ctx, &all)
if err != nil {
log.Fatalf("failed to preheat cache. fetch all: %v", err)
}
for _, m := range all {
err := c.cache.Set(ctx, m.GetId().Hex(), *m.ToModel())
if err != nil {
log.Fatalf("failed to cache item: %v", err)
}
}
}
func (c *CacheEventHandler[T, M]) HandleEvent(ctx context.Context, event *Event[T]) error {
switch event.Type {
case MongoEventDelete:
return c.cache.Delete(ctx, event.Key)
default:
return c.cache.Set(ctx, event.Key, *event.FullDocument)
}
}