fix: make ogtags and dnsbl use the Store instead of memory (#760)
Signed-off-by: Xe Iaso <me@xeiaso.net>
This commit is contained in:
parent
e870ede120
commit
7d0c58d1a8
17 changed files with 134 additions and 86 deletions
|
|
@ -43,13 +43,22 @@ func z[T any]() T { return *new(T) }
|
|||
|
||||
type JSON[T any] struct {
|
||||
Underlying Interface
|
||||
Prefix string
|
||||
}
|
||||
|
||||
func (j *JSON[T]) Delete(ctx context.Context, key string) error {
|
||||
if j.Prefix != "" {
|
||||
key = j.Prefix + key
|
||||
}
|
||||
|
||||
return j.Underlying.Delete(ctx, key)
|
||||
}
|
||||
|
||||
func (j *JSON[T]) Get(ctx context.Context, key string) (T, error) {
|
||||
if j.Prefix != "" {
|
||||
key = j.Prefix + key
|
||||
}
|
||||
|
||||
data, err := j.Underlying.Get(ctx, key)
|
||||
if err != nil {
|
||||
return z[T](), err
|
||||
|
|
@ -64,6 +73,10 @@ func (j *JSON[T]) Get(ctx context.Context, key string) (T, error) {
|
|||
}
|
||||
|
||||
func (j *JSON[T]) Set(ctx context.Context, key string, value T, expiry time.Duration) error {
|
||||
if j.Prefix != "" {
|
||||
key = j.Prefix + key
|
||||
}
|
||||
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrCantEncode, err)
|
||||
|
|
|
|||
50
lib/store/json_test.go
Normal file
50
lib/store/json_test.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package store_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis/lib/store"
|
||||
"github.com/TecharoHQ/anubis/lib/store/memory"
|
||||
)
|
||||
|
||||
func TestJSON(t *testing.T) {
|
||||
type data struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
st := memory.New(t.Context())
|
||||
db := store.JSON[data]{
|
||||
Underlying: st,
|
||||
Prefix: "foo:",
|
||||
}
|
||||
|
||||
if err := db.Set(t.Context(), "test", data{ID: t.Name()}, time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := db.Get(t.Context(), "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got.ID != t.Name() {
|
||||
t.Fatalf("got wrong data for key \"test\", wanted %q but got: %q", t.Name(), got.ID)
|
||||
}
|
||||
|
||||
if err := db.Delete(t.Context(), "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := db.Get(t.Context(), "test"); err == nil {
|
||||
t.Fatal("wanted invalid get to fail, it did not")
|
||||
}
|
||||
|
||||
if err := st.Set(t.Context(), "foo:test", []byte("}"), time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := db.Get(t.Context(), "test"); err == nil {
|
||||
t.Fatal("wanted invalid get to fail, it did not")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue