From b2acec277ee0aac0efc6a15af33314ed8007035f Mon Sep 17 00:00:00 2001 From: Adam Babik Date: Sun, 28 Jun 2020 12:01:21 +0200 Subject: [PATCH] add support for slices in XAddArgs.Values --- commands.go | 21 +++++++++++++++------ commands_test.go | 6 ++++-- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/commands.go b/commands.go index e1aba32..ddb893a 100644 --- a/commands.go +++ b/commands.go @@ -43,6 +43,9 @@ func appendArgs(dst, src []interface{}) []interface{} { dst = append(dst, s) } return dst + case []interface{}: + dst = append(dst, v...) + return dst case map[string]interface{}: for k, v := range v { dst = append(dst, k, v) @@ -1387,16 +1390,25 @@ func (c cmdable) SUnionStore(ctx context.Context, destination string, keys ...st //------------------------------------------------------------------------------ +// XAddArgs accepts values in the following formats: +// - XAddArgs.Values = []interface{}{"key1", "value1", "key2", "value2"} +// - XAddArgs.Values = []string("key1", "value1", "key2", "value2") +// - XAddArgs.Values = map[string]interface{}{"key1": "value1", "key2": "value2"} +// +// Note that map will not preserve the order of key-value pairs. type XAddArgs struct { Stream string MaxLen int64 // MAXLEN N MaxLenApprox int64 // MAXLEN ~ N ID string - Values map[string]interface{} + Values interface{} } func (c cmdable) XAdd(ctx context.Context, a *XAddArgs) *StringCmd { - args := make([]interface{}, 0, 6+len(a.Values)*2) + var values []interface{} + values = appendArgs(values, []interface{}{a.Values}) + + args := make([]interface{}, 0, 6+len(values)) args = append(args, "xadd") args = append(args, a.Stream) if a.MaxLen > 0 { @@ -1409,10 +1421,7 @@ func (c cmdable) XAdd(ctx context.Context, a *XAddArgs) *StringCmd { } else { args = append(args, "*") } - for k, v := range a.Values { - args = append(args, k) - args = append(args, v) - } + args = append(args, values...) cmd := NewStringCmd(ctx, args...) _ = c(ctx, cmd) diff --git a/commands_test.go b/commands_test.go index 5af68e0..b677e09 100644 --- a/commands_test.go +++ b/commands_test.go @@ -3413,18 +3413,20 @@ var _ = Describe("Commands", func() { Expect(err).NotTo(HaveOccurred()) Expect(id).To(Equal("1-0")) + // Values supports []interface{}. id, err = client.XAdd(ctx, &redis.XAddArgs{ Stream: "stream", ID: "2-0", - Values: map[string]interface{}{"dos": "deux"}, + Values: []interface{}{"dos", "deux"}, }).Result() Expect(err).NotTo(HaveOccurred()) Expect(id).To(Equal("2-0")) + // Value supports []string. id, err = client.XAdd(ctx, &redis.XAddArgs{ Stream: "stream", ID: "3-0", - Values: map[string]interface{}{"tres": "troix"}, + Values: []string{"tres", "troix"}, }).Result() Expect(err).NotTo(HaveOccurred()) Expect(id).To(Equal("3-0"))