-
Notifications
You must be signed in to change notification settings - Fork 0
/
persist_object_handler.go
57 lines (48 loc) · 1.29 KB
/
persist_object_handler.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
package scraper
import (
"context"
"fmt"
"log/slog"
"time"
"k8s.io/apimachinery/pkg/types"
"github.com/r2k1/pgkube/app/queries"
)
type PersistObjectHandler struct {
queries *queries.Queries
kind string
}
func NewPersistObjectHandler(queries *queries.Queries, kind string) *PersistObjectHandler {
return &PersistObjectHandler{
queries: queries,
kind: kind,
}
}
func (h *PersistObjectHandler) OnAdd(obj interface{}, isInInitialList bool) {
h.Upsert(obj)
}
func (h *PersistObjectHandler) OnUpdate(oldObj, newObj interface{}) {
h.Upsert(newObj)
}
func (h *PersistObjectHandler) OnDelete(obj interface{}) {
type UidGetter interface {
GetUID() types.UID
}
uidGetter, ok := obj.(UidGetter)
if !ok {
slog.Error("deleting object", "error", fmt.Errorf("unexpected object type: %T", obj))
return
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.queries.DeleteObject(ctx, string(uidGetter.GetUID())); err != nil {
slog.Error("deleting object", "error", err)
}
}
func (h *PersistObjectHandler) Upsert(obj interface{}) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.queries.UpsertObject(ctx, h.kind, obj); err != nil {
slog.Error("upserting object", "error", err)
return
}
}