Skip to content

Commit

Permalink
Adding support for generic command execution (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucifercr07 authored Oct 5, 2024
1 parent c9eaa28 commit f255c5f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
33 changes: 30 additions & 3 deletions internal/db/dicedb.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}
1 change: 1 addition & 0 deletions internal/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit f255c5f

Please sign in to comment.