'Problem with requesting discord cooldowns via sqlite, can't figure out the endless loop issue

I need to store cooldowns from users and then request them, so I can check if the user has the cooldown. But there is a problem, first example.

//DB thing
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('cooldowns.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Connected to the cooldowns SQlite database.');
});


function getDBCooldown(userid) 
  { return new Promise((resolve, reject) => {
  let sql = `SELECT Author author,
  Cooldown cooldown
  FROM cooldowns
  WHERE Author  = ?`;
  
  let author = userid
  db.get(sql, [author], (err, row) => {

    const now  =  new Date();
    const cooldown = new Date(row.cooldown);
    const value = date.subtract(cooldown,now);
    const days = parseInt((cooldown - now) / (1000 * 60 * 60 * 24));
    const hours = parseInt(Math.abs(cooldown - now) / (1000 * 60 * 60) % 24);
    const minutes = parseInt(Math.abs(cooldown.getTime() - now.getTime()) / (1000 * 60) % 60);
    const seconds = parseInt(Math.abs(cooldown.getTime() - now.getTime()) / (1000) % 60);
  
    if (err) {
      return console.error(err.message);
    }
    
    const expire = days + " days " +  hours + " hours " + minutes + " minutes " + seconds + " seconds "
    resolve(expire)
  });  
}) }

client.on("messageCreate", message => {


  if (message.author.bot) return;

  if (message.content.indexOf(config.prefix) !== 0) return;
  const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  if(command === 'test') {
    const dbcooldown = getDBCooldown(message.author.id)
    if (dbcooldown) {
      getDBCooldown(message.author.id)
      .then(msg => message.reply(`Cooldown is set for you. ${msg}`))
      .catch(err => console.error("Erorr getting cooldown: ", err))
      return;
    } //if cooldown is true, this statement will happen
    createDBCooldown(message.author.id, Date.now() + cooldownTime);
    // another stuff below this...

const cooldown = new Date(row.cooldown);
TypeError: Cannot read property cooldown of undefined

From what I understand and saw in several posts, issue is that cooldown is not known from the user as it does not exist in the database. Let's move on...

const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('cooldowns.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Connected to the cooldowns SQlite database.');
});

// Check User in DB
function checkDBUser(userid) {
  let sql = `SELECT Author author,
  Author author
  FROM cooldowns
  WHERE author  = ?`;
  let author = userid
  db.get(sql, [author], (err, row) => {
    if (err) {
      return console.error(err.message);
    }
    if (row.author == author) {
      return console.log(`Author ${author} is already in database!`)
    }
  });
}; 

// Create new DB user. 
function createDBUser(userid) {
  let author = userid
  let expires = null
  let MarkForDelete = false;
  db.run(`INSERT INTO cooldowns (author, cooldown, MarkForDelete) VALUES(?, ?, ?)`, [author, expires, MarkForDelete], function(err) {

   if (err) {
      return console.log(err.message);
    }
    
    console.log(`New user added to DB ${author}`);
  });
};

//Discord Message 
client.on("messageCreate", message => {


  if (message.author.bot) return;

  if (message.content.indexOf(config.prefix) !== 0) return;
  const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  if(command === 'test') {
    const DBcheck = checkDBUser(message.author.id)
    if (DBcheck) {
      return;
    }
    createDBUser(message.author.id)
    const cooldown = cooldowns.get(message.author.id); // this will check the cooldown 
    const dbcooldown = getDBCooldown(message.author.id)
    if (dbcooldown) {
      const remaining = humanizeDuration(cooldown - Date.now(), { round: true }, { units: ["d","h","m","s"] });
      getDBCooldown(message.author.id)
      .then(msg => message.reply(`Cooldown is set for you. ${msg}`))
      .catch(err => console.error("Erorr getting cooldown: ", err))
      return;
    } //if cooldown is true, this statement will happen
    createDBCooldown(message.author.id, Date.now() + cooldownTime);
if (row.author == author) {
        ^

TypeError: Cannot read property 'author' of undefined

Another error, because user/author is not known, if I use createDBUser(message.author.id) before the statement, it will endlessly create user in the DB, but problem is that user don't exist and statement will fail due error... Another problem is with the function getDBCooldown(userid), when I tried without checkDBuser statement and just added the user before dbcooldown statement, the bot will say the cooldown is something like -10000 days, also the user will be created in the DB XY times depending on how many times command was triggered. I don't know how to create "empty" user in DB meanwhile avoiding error const cooldown = new Date(row.cooldown); TypeError: Cannot read property cooldown of undefined, everything must be created before initialization and I feel that I'm trapped in the endless loop and there is no way out from it...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source