UNPKG

@egodigital/egoose

Version:

Helper classes and functions for Node.js 10 or later.

220 lines 6.85 kB
"use strict"; /** * This file is part of the @egodigital/egoose distribution. * Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/) * * @egodigital/egoose is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 3. * * @egodigital/egoose is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.sendResponse = exports.importApiErrorsSync = exports.importApiErrors = exports.createMonitoringApiResult = exports.API_ERRORS = void 0; const index_1 = require("../index"); const system_1 = require("../system"); const _ = require("lodash"); const fs_extra_1 = require("fs-extra"); const os = require("os"); const Path = require("path"); /** * Global list of API errors. */ exports.API_ERRORS = {}; function applyApiErrors(errors) { errors = index_1.asArray(errors); for (const ERR of errors) { const KEY = index_1.normalizeString(ERR.key); const CLONED_ERR = index_1.cloneObj(ERR); delete CLONED_ERR['key']; exports.API_ERRORS[KEY] = index_1.cloneObj(CLONED_ERR); } } /** * Creates an object for an result of a monitoring API endpoint. * * @param {CreateMonitoringApiResultOptions} [opts] Custom options. * * @return {Promise<MonitoringApiResult>} The promise with the result (object). */ async function createMonitoringApiResult(opts) { if (_.isNil(opts)) { opts = {}; } const USE_MEM_AVAILABLE = index_1.toBooleanSafe(opts.useMemAvailable); let cpu_load; try { cpu_load = await system_1.getCpuUsage(); } catch { } finally { if (isNaN(cpu_load)) { cpu_load = -1; } } let database_connected; try { const CONNECTION_CHECKER = opts.databaseConnectionChecker; if (!_.isNil(CONNECTION_CHECKER)) { database_connected = index_1.toBooleanSafe(await Promise.resolve(CONNECTION_CHECKER())); } } catch { database_connected = false; } let disk_space; let disk_space_used; try { const DS = await system_1.getDiskSpace(); disk_space = DS.total; disk_space_used = DS.used; } catch { } finally { if (isNaN(disk_space)) { disk_space = -1; } if (isNaN(disk_space_used)) { disk_space_used = -1; } } let ram; let ram_used; let ram_free; if (USE_MEM_AVAILABLE) { try { const MEMINFO_RESULT = await index_1.exec('cat /proc/meminfo | grep MemAvailable | cut -f2 -d : | xargs'); ram_free = parseInt(MEMINFO_RESULT.stdout.substr(0, MEMINFO_RESULT.stdout.indexOf(' ')).trim()) * 1024; } catch { } } try { if (isNaN(ram)) { ram = parseInt(index_1.toStringSafe(os.totalmem()).trim()); } if (isNaN(ram_free)) { ram_free = parseInt(index_1.toStringSafe(os.freemem()).trim()); } ram_used = ram - ram_free; } catch { } finally { if (isNaN(ram)) { ram = -1; } if (isNaN(ram_used)) { ram_used = -1; } } let version; if (index_1.toBooleanSafe(opts.withAppVersion, true)) { const APP_VERSION = index_1.getAppVersionSync({ cwd: opts.cwd, }); version = { code: APP_VERSION.code, date: !APP_VERSION.date ? APP_VERSION.date : APP_VERSION.date.toISOString(), hash: APP_VERSION.hash, name: APP_VERSION.name, }; } return { cpu_load: cpu_load, database_connected: database_connected, disk_space: disk_space, disk_space_used: disk_space_used, ram: ram, ram_used: ram_used, version: version, }; } exports.createMonitoringApiResult = createMonitoringApiResult; /** * Imports the data for 'API_ERRORS' constant. * * @param {ImportApiErrorsArgument} errors The items to import. */ async function importApiErrors(errors) { let importedErrorList; if (_.isString(errors)) { if (!Path.isAbsolute(errors)) { errors = Path.join(process.cwd(), errors); } importedErrorList = JSON.parse((await fs_extra_1.readFile(errors)).toString('utf8')); } else if (Buffer.isBuffer(errors)) { importedErrorList = JSON.parse(errors.toString('utf8')); } else { importedErrorList = errors; } applyApiErrors(importedErrorList); } exports.importApiErrors = importApiErrors; /** * Imports the data for 'API_ERRORS' constant (sync). * * @param {ImportApiErrorsArgument} errors The items to import. */ function importApiErrorsSync(errors) { let importedErrorList; if (_.isString(errors)) { if (!Path.isAbsolute(errors)) { errors = Path.join(process.cwd(), errors); } importedErrorList = JSON.parse(fs_extra_1.readFileSync(errors).toString('utf8')); } else if (Buffer.isBuffer(errors)) { importedErrorList = JSON.parse(errors.toString('utf8')); } else { importedErrorList = errors; } applyApiErrors(importedErrorList); } exports.importApiErrorsSync = importApiErrorsSync; /** * Sends an API response. * * @param {Response} res The response context. * @param {ApiResult} result The result context. * @param {SendResponseOptions} [opts] Custom options. * * @return {Response} The current response context. */ function sendResponse(res, result, opts) { if (_.isNil(opts)) { opts = {}; } const API_RESP = { data: result.data, errors: undefined, success: !!result.success, }; let code = parseInt(index_1.toStringSafe(opts.code).trim()); if (isNaN(code)) { code = 200; } if (index_1.toBooleanSafe(opts.errorKeysOnly)) { API_RESP.errors = index_1.asArray(result.errors).map(key => { return index_1.toStringSafe(key); }); } else { API_RESP.errors = index_1.asArray(result.errors).map(key => { return exports.API_ERRORS[key]; }); } return res.status(code) .header('Content-type', 'application/json; charset=utf-8') .send(Buffer.from(JSON.stringify(API_RESP), 'utf8')); } exports.sendResponse = sendResponse; //# sourceMappingURL=index.js.map