node.jsredis-streams

Unpack object into optional parameters


I'll take Redis's XADD command as an example. I'm trying to allow my write function to write objects of varying lengths to the redis stream.

Originally, the command in redis-cli looks something like this: XADD streamName objectId key1 val1 key2 val2 ...

And in NodeJS:

redisClient.xadd('streamName', 'objectId', 'key1', 'val1', 'key2', 'val2', function (err) {
  if (err) {
    console.log(err);
  }
});

And I'm trying to wrap it in a simpler method:

write(object) {
  redisClient.xadd('streamName', 'objectId', <unpack object here>, function (err) {...});
}

write({key1: 'val1', key2: 'val2', ...})

How can I unpack an object to function's optional parameters in NodeJS?


Solution

  • In order to do this I had to first turn the object into an array of its key-value pair and then unpack the array like so:

    write(object) {
      message = objectToArray(obj); // in the OP example: ["key1", "val1", "key2", "val2"]
      redisClient.xadd('streamName', 'objectId', ...message, function (err) {...});
    }