From f255c5fb0f8f1f6441bd63a5a9ccbde87795467f Mon Sep 17 00:00:00 2001 From: Prashant Shubham Date: Sat, 5 Oct 2024 23:34:06 +0530 Subject: [PATCH] Adding support for generic command execution (#27) --- internal/db/dicedb.go | 33 ++++++++++++++++++++++++++++++--- internal/server/http.go | 1 + 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/internal/db/dicedb.go b/internal/db/dicedb.go index 71d4901..7da8f9f 100644 --- a/internal/db/dicedb.go +++ b/internal/db/dicedb.go @@ -12,11 +12,14 @@ import ( "os" "server/config" "server/util/cmds" + "strings" "time" dicedb "github.com/dicedb/go-dice" ) +const RespNil = "(nil)" + type DiceDB struct { Client *dicedb.Client Ctx context.Context @@ -60,7 +63,7 @@ func (db *DiceDB) ExecuteCommand(command *cmds.CommandRequest) (interface{}, err res, err := db.Client.Do(db.Ctx, args...).Result() if errors.Is(err, dicedb.Nil) { - return nil, errors.New("(nil)") + return RespNil, nil } if err != nil { @@ -74,13 +77,37 @@ func (db *DiceDB) ExecuteCommand(command *cmds.CommandRequest) (interface{}, err case []byte: return string(v), nil case []interface{}: + return renderListResponse(v) case int64: return fmt.Sprintf("%v", v), nil case nil: - return "(nil)", nil + return RespNil, nil default: return fmt.Sprintf("%v", v), nil } +} + +func renderListResponse(items []interface{}) (string, error) { + if len(items)%2 != 0 { + return "", fmt.Errorf("(error) invalid result format") + } + + var builder strings.Builder + for i := 0; i < len(items); i += 2 { + field, ok1 := items[i].(string) + value, ok2 := items[i+1].(string) + + // Check if both field and value are valid strings + if !ok1 || !ok2 { + return "", fmt.Errorf("(error) invalid result type") + } + + // Append the formatted field and value + _, err := fmt.Fprintf(&builder, "%d) \"%s\"\n%d) \"%s\"\n", i+1, field, i+2, value) + if err != nil { + return "", err + } + } - return nil, fmt.Errorf("(error) invalid result type") + return builder.String(), nil } diff --git a/internal/server/http.go b/internal/server/http.go index 00d6a3e..c665277 100644 --- a/internal/server/http.go +++ b/internal/server/http.go @@ -111,6 +111,7 @@ func (s *HTTPServer) CliHandler(w http.ResponseWriter, r *http.Request) { resp, err := s.DiceClient.ExecuteCommand(diceCmd) if err != nil { + slog.Error("error: failure in executing command", "error", slog.Any("err", err)) http.Error(w, errorResponse(err.Error()), http.StatusBadRequest) return }