-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
cache.go
59 lines (49 loc) · 1.14 KB
/
cache.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
58
59
package graphql
import (
"context"
"encoding/json"
"time"
"go.uber.org/zap"
)
// Cache is a basic type as defined by gqlgen.
type Cache struct {
}
// NewCache creates a new cache.
func NewCache() (*Cache, error) {
return &Cache{}, nil
}
// Add inserts a key value pair into the database.
func (c *Cache) Add(ctx context.Context, hash string, query interface{}) {
blob, err := json.Marshal(query)
if err != nil {
log.Errorw("could not marshal query", zap.Error(err))
}
_, err = db.ExecContext(
ctx,
`
INSERT INTO cache(key, value, modified_at)
VALUES ($1, $2, $3)
ON CONFLICT (key) DO UPDATE
SET (value, modified_at) = ($2, $3)
WHERE cache.key = $1;
`,
hash,
blob,
time.Now())
if err != nil {
log.Errorw("could not insert key", zap.Error(err))
}
}
// Get retrieves a value by a key.
func (c *Cache) Get(ctx context.Context, hash string) (interface{}, bool) {
var value []byte
row := db.QueryRowContext(ctx, "SELECT value FROM cache WHERE key = $1", hash)
if err := row.Scan(&value); err != nil {
return "", false
}
var i interface{}
if err := json.Unmarshal(value, &i); err != nil {
return "", false
}
return i, true
}