moved config initialization into own function

This commit is contained in:
Daniel Sommer 2022-02-25 15:41:11 +01:00
parent 4d2dcbf4f0
commit 2139b0b111

View file

@ -1,12 +1,14 @@
// requirements
const server = require('./libs/server.js');
const util = require('./libs/util.js');
const logger = require('./libs/logger.js'); const logger = require('./libs/logger.js');
const util = require('./libs/util.js');
const cli = require('./libs/cli.js');
const server = require('./libs/server.js');
const packageJSON = require('./package'); const packageJSON = require('./package');
const INTERRUPTS = ['SIGINT', 'SIGTERM']; const INTERRUPTS = ['SIGINT', 'SIGTERM'];
global.config = process.argv[2] || __dirname + '/config.json'; global.config = undefined;
global.appName = packageJSON.name;
global.appVersion = packageJSON.version;
// handle interrupts // handle interrupts
handleInterrupts(); handleInterrupts();
@ -15,31 +17,26 @@ handleInterrupts();
main() main()
.catch(exit); .catch(exit);
// main - let's get this party started
async function main() { async function main() {
const config = await util.fileExists(global.config); await setGlobalConfig();
global.config = require(config.path);
global.config.path = config.path;
logger.initialize(); logger.initialize();
logger.info(global.appName + ' ' + global.appVersion + ' starting...');
if (await cli.handleArguments()) {
exit();
}
logger.info(await server.start()); logger.info(await server.start());
server.handleRequests(); server.handleRequests();
} }
// ... and it all comes crashing down async function setGlobalConfig() {
function exit(err, code) { let config = __dirname + '/config.json';
if (code === undefined) { let index = process.argv.indexOf(cli.ARG_CONFIG);
code = 0; if (index >= 0 && process.argv.length >= index + 1) {
if (err !== undefined) { config = process.argv[index + 1];
code = 1;
}
} }
if (err) { config = await util.fileExists(config);
logger.error(err); global.config = require(config.path);
logger.error(packageJSON.name + ' ended due to an error'); global.config.path = config.path;
} else {
logger.info(packageJSON.name + ' shutting down gracefully')
}
process.exit(code);
} }
function handleInterrupts() { function handleInterrupts() {
@ -49,3 +46,21 @@ function handleInterrupts() {
}); });
} }
} }
function exit(err, code) {
if (code === undefined) {
code = 0;
if (err !== undefined) {
code = 1;
}
}
if (err) {
logger.error(err);
logger.error(global.appName + ' ' + global.appVersion + ' ended due to an error');
} else {
logger.info(global.appName + ' ' + global.appVersion + ' shutting down gracefully')
}
process.exit(code);
}