~evanj/cms

ref: afc228cb59683180b3b2957aceb6bf1aa0bf0d0e cms/internal/s/cache/space.go -rw-r--r-- 1.7 KiB
afc228cbEvan J Feat(db): Tweaking db.SetMaxOpenConns, db.SetMaxIdleConns, and 1 year, 26 days 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package cache

import (
	"fmt"

	"git.sr.ht/~evanj/cms/internal/m/space"
	"git.sr.ht/~evanj/cms/internal/m/user"
	"git.sr.ht/~evanj/cms/internal/s/db"
)

func (c *Cache) space(breakCache bool, key string, getter func() (space.Space, error)) (space.Space, error) {
	var v *db.Space
	if err := c.cache(breakCache, key, &v, func() (interface{}, error) { return getter() }); err != nil {
		return nil, err
	}
	return v, nil
}

func (c *Cache) SpaceNew(user user.User, name, desc string) (space.Space, error) {
	thing, err := c.db.SpaceNew(user, name, desc)
	if err != nil {
		return nil, err
	}

	return c.space(
		true,
		fmt.Sprintf("space::%s::%s::%s", c.baseKey, user.ID(), thing.ID()),
		func() (space.Space, error) { return thing, err },
	)
}

func (c *Cache) SpaceGet(user user.User, thingID string) (space.Space, error) {
	return c.space(
		false,
		fmt.Sprintf("space::%s::%s::%s", c.baseKey, user.ID(), thingID),
		func() (space.Space, error) { return c.db.SpaceGet(user, thingID) },
	)
}

func (c *Cache) SpaceUpdate(user user.User, prev space.Space, name, desc string) (space.Space, error) {
	next, err := c.db.SpaceUpdate(user, prev, name, desc)
	if err != nil {
		return nil, err
	}

	return c.space(
		true,
		fmt.Sprintf("space::%s::%s::%s", c.baseKey, user.ID(), next.ID()),
		func() (space.Space, error) { return next, err },
	)
}

func (c *Cache) SpaceDelete(u user.User, s space.Space) error {
	key := fmt.Sprintf("space::%s::%s::%s", c.baseKey, u.ID(), s.ID())

	var deleteErr error
	_, _ = c.space(
		true,
		key,
		func() (space.Space, error) {
			deleteErr = c.db.SpaceDelete(u, s)
			return nil, deleteErr
		},
	)

	if deleteErr != nil {
		return deleteErr
	}

	return c.mc.Delete(key)
}

// TODO: SpacesPerUser