How to query redis hmget and get or convert the result to get it as object (Node.js)

150 Views Asked by At

Consider the following.

const user = {
    name: 'foo',
    email: '[email protected]',
    level: 15,
};

await ioredis.hmset('user:1', user);

const [name, email, level] = await ioredis.hmget('user:1', ['name', 'email', 'level']);

const reconstructUser = {
    name,
    email,
    level,
};

Is there a way to simplify the process here of hmget? Because now it's "only 3" but it can also be 10 values that I will need to remap in every query, and as you can see I also need to type their names again and again with the risk for a typo in every part.

A bonus would be a way to also recast it if it's not String (for example level in this case), or give default value in case it's null.

1

There are 1 best solutions below

0
On

You can use Object.keys to store the keys of the user object and then loop through the hmget result array.

const user = {
  name: 'foo',
  email: '[email protected]',
  level: 15,
};

await ioredis.hmset('user:1', user);

const keys = Object.keys (user);

const userValue = await ioredis.hmget('user:1', keys);

let reconstructUser = {};

for (let i = 0; i < userValue.length; i++) {
  reconstructUser[keys[i]] = userValue[i];
}