Skip to content

Commit

Permalink
checkMongoDB復活
Browse files Browse the repository at this point in the history
  • Loading branch information
mei23 committed Sep 17, 2023
1 parent 46c4138 commit 274bf54
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import loadConfig from './config/load';
import { Config } from './config/types';
import { envOption } from './env';
import { showMachineInfo } from './misc/show-machine-info';
import { checkMongoDB } from './misc/check-mongodb';

const logger = new Logger('core', 'cyan');
const bootLogger = logger.createSubLogger('boot', 'magenta', false);
Expand Down Expand Up @@ -240,6 +241,14 @@ async function init(config: Config) {
nodejsLogger.info(`Version ${runningNodejsVersion.join('.')}`);

await showMachineInfo(bootLogger);

// Try to connect to MongoDB
try {
await checkMongoDB(config, bootLogger);
} catch (e) {
bootLogger.error('Cannot connect to database', null, true);
process.exit(1);
}
}

async function spawnWorkers(config: Config) {
Expand Down
41 changes: 41 additions & 0 deletions src/misc/check-mongodb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { nativeDbConn } from '../db/mongodb';
import { Config } from '../config/types';
import Logger from '../services/logger';
import { lessThan } from '../prelude/array';

const requiredMongoDBVersion = [3, 6];

export function checkMongoDB(config: Config, logger: Logger) {
return new Promise((res, rej) => {
const mongoDBLogger = logger.createSubLogger('db');
const u = config.mongodb.user ? encodeURIComponent(config.mongodb.user) : null;
const p = config.mongodb.pass ? encodeURIComponent(config.mongodb.pass) : null;
const path = config.mongodb.path ? encodeURIComponent(config.mongodb.path) : null;
const peer = path || `${config.mongodb.host}:${config.mongodb.port}`;

const uri = `mongodb://${u && p ? `${u}:${p}@` : ''}${peer}/${config.mongodb.db}`;

mongoDBLogger.info(`Connecting to ${uri} ...`);

nativeDbConn().then(db => {
mongoDBLogger.succ('Connectivity confirmed');

db.admin().serverInfo().then(x => {
const version = x.version as string;
mongoDBLogger.info(`Version: ${version}`);
if (lessThan(version.split('.').map(x => parseInt(x, 10)), requiredMongoDBVersion)) {
mongoDBLogger.error(`MongoDB version is less than ${requiredMongoDBVersion.join('.')}. Please upgrade it.`);
rej('outdated version');
} else {
res();
}
}).catch(err => {
mongoDBLogger.error(`Failed to fetch server info: ${err.message}`);
rej(err);
});
}).catch(err => {
mongoDBLogger.error(err.message);
rej(err);
});
});
}

0 comments on commit 274bf54

Please sign in to comment.