Search code examples
node.jsnode-red

Reading and saving a list from global variable


Not the best practice, but what I want is to store an array of objects containing type and datetime. I use it for sending out mail, and I dont want to spam mail, but limit so a type only sends out mail every 15 minutes:

var sendMail = true;

var emailType = "test" // set for test

var log = []
var tempLog = global.get("emaillog")

// read the log from global variables
if ( typeof tempLog !== 'undefined' && tempLog )
{
  log = tempLog
}

// search the log
for (var i = 0, len = log.length; i < len; i++) 
{
    var logElement = log[i]
    var logElementEmailType = logElement.Type
    var logElementEmailDateTime = logElement.DateTime

    var dif = new Date() - logElementEmailDateTime;

    if (logElementEmailType == emailType && Math.abs(dif/1000) < (60*5))
    {
        sendMail = false
    }
}

// add to log
var newLogElement = 
{
    DateTime: new Date(),
    Type: mailType
}

log.push(newLogElement)

// save global variable
global.set("maillog",log)

But this not work, spamming me down hard :D


Solution

  • I believe that dif is in miliseconds. You divide it by 1000 and get microseconds.