~evanj/cms

ref: 27de4d9c907e2258a828fbfcda8f22b910df0f63 cms/internal/s/cache/cache.go -rw-r--r-- 1.1 KiB
27de4d9cEvan M Jones Feat(spaces): Added the ability to copy an entire space. 1 year, 7 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
52
53
54
55
56
57
58
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, error) {
	c := &Cache{
		db,
		log,
		key,
		memcache.New(memcacheServer),
		db,
	}
	return c, 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.
		c.log.Println("put", key)
		m = &memcache.Item{Value: bytes}
	}

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

	c.log.Println("got", key)
	return nil
}