incapsulating redis hmset in iced coffee script function

108 views Asked by At

I want to incapsulate redis hmset.

exports.hmset = (name, autocb, params...)=>
    await client.hmset name, params, defer(err)
    throw err if err

I have that params is array like ['fooKey', 'fooValue', 'barKey', 'barValue']. But then I have data in redis database on name key:

{'0' : 'fooKey', '1' : 'fooValue', '2' : 'barKey', '3': 'barValue'}

But I want it to be:

{'fooKey' : 'fooValue', 'barKey' : 'barValue'}

I understand that I have to pass them into client.hmset not like an array ['fooKey', 'fooValue', 'barKey', 'barValue'] but just like args: 'fooKey', 'fooValue', 'barKey', 'barValue'. But how to pass them through wrapping exports.hmset function when args length is various?

2

There are 2 answers

0
Linus Thiel On BEST ANSWER

As I understand it, you are using the varargs convention of calling hmset. You use a splat to collect the arguments in an array, and then you pass the array as an argument to node_redis -- which also supports the object convention, where you pass a plain object with the keys and their values. That's why you get your redis hash with positional keys, since if you treat a javascript array as an object, that's what you have.

What you need to do is simply to splat the params again when calling redis:

exports.hmset = (name, autocb, params...)=>
    await client.hmset name, params..., defer(err)
    throw err if err

Now, coffeescript will pass that array as varargs to the "real" hmset. As an added bonus, you can also still use the "params as an object" convention, which is arguably more elegant.

0
funny_falcon On

Do you understand that throw err will not work in IcedCoffeeScript as you expect it to work? It will raise error in an event loop, so that you could not catch it with "try" in your code.