90 lines
1.6 KiB
Go
90 lines
1.6 KiB
Go
package valkeydb
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
type DbItem map[string]any
|
|
|
|
type ValkeyDB struct {
|
|
client *redis.Client
|
|
name string
|
|
}
|
|
|
|
func NewValkeyDB(client *redis.Client, dbName string) *ValkeyDB {
|
|
return &ValkeyDB{
|
|
client: client,
|
|
name: dbName,
|
|
}
|
|
}
|
|
|
|
func (db *ValkeyDB) GetName() string {
|
|
return db.name
|
|
}
|
|
|
|
type Table[T any] struct {
|
|
Name string
|
|
db *ValkeyDB
|
|
}
|
|
|
|
func NewTable[T any](db *ValkeyDB, tableName string) *Table[T] {
|
|
return &Table[T]{
|
|
Name: fmt.Sprintf("%s:%s", db.GetName(), tableName),
|
|
db: db,
|
|
}
|
|
}
|
|
|
|
func (t *Table[T]) createItemHash(id string) string {
|
|
return fmt.Sprintf("%s:%s", t.Name, id)
|
|
}
|
|
|
|
func (t *Table[T]) createNewId() (string, string) {
|
|
newId := uuid.New().String()
|
|
hash := t.createItemHash(newId)
|
|
return hash, newId
|
|
}
|
|
|
|
func (t *Table[T]) Insert(ctx context.Context, item *T) (string, error) {
|
|
hash, newId := t.createNewId()
|
|
jItem, err := json.Marshal(t)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
cmd := t.db.client.HSet(ctx, hash, "$", string(jItem))
|
|
if cmd.Err() != nil {
|
|
return "", err
|
|
}
|
|
return newId, nil
|
|
}
|
|
|
|
func (t *Table[T]) Get(ctx context.Context, id string) (*T, error) {
|
|
hash := t.createItemHash(id)
|
|
cmd := t.db.client.HGet(ctx, hash, "$")
|
|
err := cmd.Err()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var res T
|
|
err = json.Unmarshal([]byte(cmd.Val()), &res)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &res, nil
|
|
}
|
|
|
|
func (t *Table[T]) Remove(ctx context.Context, id string) error {
|
|
hash := t.createItemHash(id)
|
|
cmd := t.db.client.HDel(ctx, hash)
|
|
err := cmd.Err()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|