Implementing APPEND command

This commit is contained in:
DMcP89
2024-06-26 23:01:01 -04:00
committed by Kelvin Mwinuka
parent eb80a8dbb1
commit b36d5056af
2 changed files with 36 additions and 4 deletions

View File

@@ -168,7 +168,30 @@ func handleSubStr(params internal.HandlerFuncParams) ([]byte, error) {
}
func handleAppend(params internal.HandlerFuncParams) ([]byte, error) {
return []byte("Hello World"), nil
keys, err := appendKeyFunc(params.Command)
if err != nil {
return nil, err
}
key := keys.WriteKeys[0]
keyExists := params.KeysExist(keys.WriteKeys)[key]
value := params.Command[2]
if !keyExists {
if err = params.SetValues(params.Context, map[string]interface{}{
key: internal.AdaptType(value),
}); err != nil {
return nil, err
}
return []byte(fmt.Sprintf("$%d\r\n%s\r\n", len(value), value)), nil
}
currentValue := params.GetValues(params.Context, []string{key})[key]
newValue := fmt.Sprintf("%v%s", currentValue, value)
if err = params.SetValues(params.Context, map[string]interface{}{
key: internal.AdaptType(newValue),
}); err != nil {
return nil, err
}
return []byte(fmt.Sprintf("$%d\r\n%s\r\n", len(newValue), newValue)), nil
}
func Commands() []internal.Command {
@@ -210,5 +233,14 @@ Overwrites part of a string value with another by offset. Creates the key if it
KeyExtractionFunc: subStrKeyFunc,
HandlerFunc: handleSubStr,
},
{
Command: "append",
Module: constants.StringModule,
Categories: []string{constants.StringCategory, constants.ReadCategory, constants.SlowCategory},
Description: `(APPEND key value) If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so APPEND will be similar to [SET] in this special case.`,
Sync: true,
KeyExtractionFunc: appendKeyFunc,
HandlerFunc: handleAppend,
},
}
}

View File

@@ -55,12 +55,12 @@ func subStrKeyFunc(cmd []string) (internal.KeyExtractionFuncResult, error) {
}
func appendKeyFunc(cmd []string) (internal.KeyExtractionFuncResult, error) {
if len(cmd) != 4 {
if len(cmd) != 3 {
return internal.KeyExtractionFuncResult{}, errors.New(constants.WrongArgsResponse)
}
return internal.KeyExtractionFuncResult{
Channels: make([]string, 0),
ReadKeys: cmd[1:2],
WriteKeys: make([]string, 0),
ReadKeys: make([]string, 0),
WriteKeys: cmd[1:2],
}, nil
}