onasty/internal/store/rdb/notecache/notecache.go (view raw)
Smirnov Oleksandr
Smirnov Oleksandr
ss2316544@gmail.com refactor: fix annoyances (#97)..., 1 year ago
ss2316544@gmail.com refactor: fix annoyances (#97)..., 1 year ago
| 1 | package notecache |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/gob" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/olexsmir/onasty/internal/models" |
| 11 | "github.com/olexsmir/onasty/internal/store/rdb" |
| 12 | ) |
| 13 | |
| 14 | type NoteCacher interface { |
| 15 | SetNote(ctx context.Context, slug string, note models.Note) error |
| 16 | GetNote(ctx context.Context, slug string) (models.Note, error) |
| 17 | } |
| 18 | |
| 19 | type NoteCache struct { |
| 20 | rdb *rdb.DB |
| 21 | ttl time.Duration |
| 22 | } |
| 23 | |
| 24 | func New(rdb *rdb.DB, ttl time.Duration) *NoteCache { |
| 25 | return &NoteCache{ |
| 26 | rdb: rdb, |
| 27 | ttl: ttl, |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | func (n *NoteCache) SetNote(ctx context.Context, slug string, note models.Note) error { |
| 32 | var buf bytes.Buffer |
| 33 | if err := gob.NewEncoder(&buf).Encode(note); err != nil { |
| 34 | return err |
| 35 | } |
| 36 | |
| 37 | _, err := n.rdb.Set(ctx, getKey(slug), buf.Bytes(), n.ttl).Result() |
| 38 | return err |
| 39 | } |
| 40 | |
| 41 | func (n *NoteCache) GetNote(ctx context.Context, slug string) (models.Note, error) { |
| 42 | val, err := n.rdb.Get(ctx, getKey(slug)).Bytes() |
| 43 | if err != nil { |
| 44 | return models.Note{}, err |
| 45 | } |
| 46 | |
| 47 | var note models.Note |
| 48 | if err = gob.NewDecoder(bytes.NewReader(val)).Decode(¬e); err != nil { |
| 49 | return models.Note{}, err |
| 50 | } |
| 51 | |
| 52 | return note, err |
| 53 | } |
| 54 | |
| 55 | func getKey(slug string) string { |
| 56 | var sb strings.Builder |
| 57 | sb.WriteString("note:") |
| 58 | sb.WriteString(slug) |
| 59 | return sb.String() |
| 60 | } |