UNPKG

@coko/server

Version:

Reusable server for use by Coko's projects

68 lines 2.51 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkConnections = void 0; const config_1 = __importDefault(require("../configManager/config")); const db_1 = __importDefault(require("../db/db")); const internals_1 = __importDefault(require("../logger/internals")); const fileStorage_1 = __importDefault(require("../fileStorage")); class DatabaseConnectionError extends Error { constructor(message) { super(message); this.name = 'DatabaseConnectionError'; } } const sleep = (ms) => new Promise(resolve => { setTimeout(resolve, ms); }); const checkDbConnection = async () => { const retries = 5; const iterable = Array.from({ length: retries }, (_, i) => i + 1); /** * Use for of deliberately, so that each iteration awaits before moving to * the next one. */ for (const attempt of iterable) { try { if (attempt > 1) { internals_1.default.wait(`Connecting to database: Attempt ${attempt}/${retries}`); } /* eslint-disable-next-line no-await-in-loop */ await db_1.default.raw('SELECT 1+1 AS result'); internals_1.default.success('Database connection successful'); break; } catch (e) { if (attempt === retries) { internals_1.default.error('Could not establish connection to the database'); throw new DatabaseConnectionError(e.message); } else { const timeout = attempt * 1000; /* eslint-disable-next-line no-await-in-loop */ await sleep(timeout); } } } }; const checkConnections = async () => { internals_1.default.section('Checking external connections'); await checkDbConnection(); if (config_1.default.get('fileStorage')) { try { await fileStorage_1.default.healthCheck(); internals_1.default.success('File storage connection successful'); } catch (e) { internals_1.default.error('Could not establish connection to file storage'); throw e; } } else { internals_1.default.warn('Skipping file storage as it is disabled'); } }; exports.checkConnections = checkConnections; //# sourceMappingURL=checkConnections.js.map