node.jsredisioredis

Set Expiry time of hsetnx


How to Set expiry time of hsetnx (https://redis.io/commands/hsetnx/) to be 1 hour. Currently i don't see a param where i can set expiry time to it.

const IoRedis = require("ioredis");
const redis = new IoRedis();

var message = {
  "jobdid": "JCLT",
  "email": "a@k.com"
}

checkForDuplicate(message);

async function checkForDuplicate(message){

  const email    = message.email.toLowerCase();
    const jobdid = message.jobdid.toLowerCase();
    const resp   = await redis.hsetnx(`jobs:${email}`, jobdid, +new Date());

    console.log(resp);
}

Solution

  • If you don't need to enumerate the jobs separately, then you don't really need a hash; you can just se a sequence of setnx + expire. You don't need a MULTI since setnx will only return 1 exactly once, so a second concurrent caller will never get to the expire.

    const IoRedis = require("ioredis");
    const redis = new IoRedis();
    
    var message = {
      jobdid: "JCLT",
      email: "a@k.com",
    };
    
    checkForDuplicate(message);
    
    async function checkForDuplicate(message) {
      const key = `jobs:${message.email.toLowerCase()}:${message.jobdid.toLowerCase()}`;
      const didSet = await redis.setnx(key, +new Date());
      if (didSet) {
        // We did set this, we're okay to set expiry too
        await redis.expire(key, 3600);
      }
      return didSet;
    }