~evanj/cms

ref: ed17a2199584ba94d1ca44e9002b52c48b2c02fa cms/internal/s/cache/cache.go -rw-r--r-- 1.0 KiB
ed17a219Evan J Feat(context): Thread context throughout data layer. TODO: Update 1 year, 2 months ago
                                                                                
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 cache

import (
	"encoding/json"
	"log"

	"git.sr.ht/~evanj/cms/internal/s/db"
	"github.com/bradfitz/gomemcache/memcache"
)

type Cache struct {
	*db.DB
	log     *log.Logger
	baseKey string
	mc      *memcache.Client
	db      *db.DB
}

func New(log *log.Logger, db *db.DB, key string, memcacheServer string) *Cache {
	return &Cache{db, log, key, memcache.New(memcacheServer), db}
}

func (c *Cache) Setup() error { return c.mc.Ping() }

func (c *Cache) cache(breakCache bool, key string, v interface{}, getter func() (interface{}, error)) error {
	m, err := c.mc.Get(key)
	if err != nil || breakCache {
		thing, err := getter()
		if err != nil {
			return err
		}

		bytes, err := json.Marshal(thing)
		if err != nil {
			return err
		}

		if err := c.mc.Set(&memcache.Item{Key: key, Value: bytes}); err != nil {
			return err
		}

		// TODO: On put we transform to json AND decode to json. Fix this.
		m = &memcache.Item{Value: bytes}
	}

	if err := json.Unmarshal(m.Value, &v); err != nil {
		return err
	}

	return nil
}