Monday, March 14, 2022

[SOLVED] Is it possible to share constant variable which its value receive from the Database?

Issue

I'm created a cron job with Cron module. Currently, I declared that cron job in crawler.js file and its cron rules in settings.js file just like below:

File settings.js:

const cronCrawlItemsRule = '0 */10 * * * *'

module.exports = { cronCrawlItemsRule  }

File crawler.js:

const connectDB = require('./config/db');
connectDB();

const { cronCrawlItemsRule } = require './settings.js';

const crawlItems = new CronJob(cronCrawlItemsRule, async function() {
  // do stuff here and save to DB that connected above.
})

Problem: I want to save cron rules to DB, then whenever I start the server, get those cron rules and the crons will run follow that rules. Remind that those rules will be got once the server is started.

Is it possible to do this? I've tried like below:

const connectDB = require('./config/db');
connectDB();

const { cronCrawlItemsRule } = require './settings.js';

(async() => {
  const rule = (await Config.findOne({...}))?._doc.value || cronCrawlItemsRule; // <- here
  const crawlItems = new CronJob(rule, async function() { // <- and here
    // do stuff here and save to DB that connected above.
})
})()

but I have to get those rules from DB again whenever I need them in other files.

Does anyone know how to do this? Thanks in advance.


Solution

To who is stuck at the same problem. After spending few days, I figured out the solution.

  • In settings.js file, exports a function to fetch settings from DB like below, it means that you will exports variable named cronCrawlItemsRule whenever fetchSettingFromDb function get called:
const setting1 = '...';
const setting2 = '...';
const fetchSettingFromDb = async () => {
  module.exports.cronCrawlItemsRule = (await Config.findOne({...}))?._doc.value || '0 */10 * * * *';
}


module.exports = { setting1, setting2, fecthSettingFromDb }
  • Make sure your app is connected to DB by put await before connectDb function in the crawler.js file.
const connectDB = require('./config/db');

// Because this "cronCrawlItemsRule" variable is not declared nor exported in settings.js file.
// Required it like below can raise error.
// const { cronCrawlItemsRule } = require './settings.js' // DON'T USE THIS
const settings = require './settings.js'; //<= USE THIS

// But which variable exported from the begin in settings.js file can be required as usual
const { setting1, setting2, fetchSettingFromDb } = require('./settings');

(async () => {
  await connectDB();
  
  await fecthSettingFromDb();
  // It works thanks to settings.cronCrawlItemsRule;
  const crawlItems = new CronJob(settings.cronCrawlItemsRule, async function() {
    // do stuff here and save to DB that connected above.
})
})()


Answered By - Hùng H.
Answer Checked By - Senaida (WPSolving Volunteer)