const chokidar = require('chokidar'); const { exec } = require('child_process'); const nodemon = require('nodemon'); const { logger } = require('./src/utils/logger'); const nodeEnv = process.env.NODE_ENV || 'dev_stage'; const childEnv = { ...process.env, NODE_ENV: nodeEnv }; const log = logger.child({ module: 'watcher' }); function logCommandResult(error, stdout, stderr, successMessage) { const output = stdout && stdout.trim(); const errorOutput = stderr && stderr.trim(); if (output) { log.info({ output }, successMessage); } if (error) { log.error( { err: error, stderr: errorOutput }, 'Watched database command failed', ); } else if (errorOutput) { log.warn({ stderr: errorOutput }, 'Watched database command wrote stderr'); } } const migrationsWatcher = chokidar.watch('./src/db/migrations', { persistent: true, ignoreInitial: true }); migrationsWatcher.on('add', (filePath) => { log.info({ filePath }, 'New migration file detected'); exec('npm run db:migrate', { env: childEnv }, (error, stdout, stderr) => { logCommandResult(error, stdout, stderr, 'Migration command completed'); }); }); const seedersWatcher = chokidar.watch('./src/db/seeders', { persistent: true, ignoreInitial: true }); seedersWatcher.on('add', (filePath) => { log.info({ filePath }, 'New seed file detected'); exec('npm run db:seed', { env: childEnv }, (error, stdout, stderr) => { logCommandResult(error, stdout, stderr, 'Seeder command completed'); }); }); nodemon({ script: './src/index.js', env: childEnv, ignore: ['./src/db/migrations', './src/db/seeders'], delay: '500' }); nodemon.on('start', () => { log.info({ nodeEnv }, 'Nodemon started'); }); nodemon.on('restart', (files) => { log.info({ files }, 'Nodemon restarted due to file changes'); }); nodemon.on('crash', () => { log.error('Nodemon app crashed'); });