UNPKG

6.66 kBJavaScriptView Raw
1"use strict";
2/**
3 * This file is part of the @egodigital/egoose distribution.
4 * Copyright (c) e.GO Digital GmbH, Aachen, Germany (https://www.e-go-digital.com/)
5 *
6 * @egodigital/egoose is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation, version 3.
9 *
10 * @egodigital/egoose is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18Object.defineProperty(exports, "__esModule", { value: true });
19const index_1 = require("../index");
20const system_1 = require("../system");
21const _ = require("lodash");
22const fs_extra_1 = require("fs-extra");
23const os = require("os");
24const Path = require("path");
25/**
26 * Global list of API errors.
27 */
28exports.API_ERRORS = {};
29function applyApiErrors(errors) {
30 errors = index_1.asArray(errors);
31 for (const ERR of errors) {
32 const KEY = index_1.normalizeString(ERR.key);
33 const CLONED_ERR = index_1.cloneObj(ERR);
34 delete CLONED_ERR['key'];
35 exports.API_ERRORS[KEY] = index_1.cloneObj(CLONED_ERR);
36 }
37}
38/**
39 * Creates an object for an result of a monitoring API endpoint.
40 *
41 * @param {CreateMonitoringApiResultOptions} [opts] Custom options.
42 *
43 * @return {Promise<MonitoringApiResult>} The promise with the result (object).
44 */
45async function createMonitoringApiResult(opts) {
46 if (_.isNil(opts)) {
47 opts = {};
48 }
49 const USE_MEM_AVAILABLE = index_1.toBooleanSafe(opts.useMemAvailable);
50 let cpu_load;
51 try {
52 cpu_load = await system_1.getCpuUsage();
53 }
54 catch (_a) { }
55 finally {
56 if (isNaN(cpu_load)) {
57 cpu_load = -1;
58 }
59 }
60 let database_connected;
61 try {
62 const CONNECTION_CHECKER = opts.databaseConnectionChecker;
63 if (!_.isNil(CONNECTION_CHECKER)) {
64 database_connected = index_1.toBooleanSafe(await Promise.resolve(CONNECTION_CHECKER()));
65 }
66 }
67 catch (_b) {
68 database_connected = false;
69 }
70 let disk_space;
71 let disk_space_used;
72 try {
73 const DS = await system_1.getDiskSpace();
74 disk_space = DS.total;
75 disk_space_used = DS.used;
76 }
77 catch (_c) { }
78 finally {
79 if (isNaN(disk_space)) {
80 disk_space = -1;
81 }
82 if (isNaN(disk_space_used)) {
83 disk_space_used = -1;
84 }
85 }
86 let ram;
87 let ram_used;
88 let ram_free;
89 if (USE_MEM_AVAILABLE) {
90 try {
91 const MEMINFO_RESULT = await index_1.exec('cat /proc/meminfo | grep MemAvailable | cut -f2 -d : | xargs');
92 ram_free = parseInt(MEMINFO_RESULT.stdout.substr(0, MEMINFO_RESULT.stdout.indexOf(' ')).trim()) * 1024;
93 }
94 catch (_d) { }
95 }
96 try {
97 if (isNaN(ram)) {
98 ram = parseInt(index_1.toStringSafe(os.totalmem()).trim());
99 }
100 if (isNaN(ram_free)) {
101 ram_free = parseInt(index_1.toStringSafe(os.freemem()).trim());
102 }
103 ram_used = ram - ram_free;
104 }
105 catch (_e) { }
106 finally {
107 if (isNaN(ram)) {
108 ram = -1;
109 }
110 if (isNaN(ram_used)) {
111 ram_used = -1;
112 }
113 }
114 let version;
115 if (index_1.toBooleanSafe(opts.withAppVersion, true)) {
116 const APP_VERSION = index_1.getAppVersionSync({
117 cwd: opts.cwd,
118 });
119 version = {
120 date: !APP_VERSION.date ? APP_VERSION.date
121 : APP_VERSION.date.toISOString(),
122 hash: APP_VERSION.hash,
123 };
124 }
125 return {
126 cpu_load: cpu_load,
127 database_connected: database_connected,
128 disk_space: disk_space,
129 disk_space_used: disk_space_used,
130 ram: ram,
131 ram_used: ram_used,
132 version: version,
133 };
134}
135exports.createMonitoringApiResult = createMonitoringApiResult;
136/**
137 * Imports the data for 'API_ERRORS' constant.
138 *
139 * @param {ImportApiErrorsArgument} errors The items to import.
140 */
141async function importApiErrors(errors) {
142 let importedErrorList;
143 if (_.isString(errors)) {
144 if (!Path.isAbsolute(errors)) {
145 errors = Path.join(process.cwd(), errors);
146 }
147 importedErrorList = JSON.parse((await fs_extra_1.readFile(errors)).toString('utf8'));
148 }
149 else if (Buffer.isBuffer(errors)) {
150 importedErrorList = JSON.parse(errors.toString('utf8'));
151 }
152 else {
153 importedErrorList = errors;
154 }
155 applyApiErrors(importedErrorList);
156}
157exports.importApiErrors = importApiErrors;
158/**
159 * Imports the data for 'API_ERRORS' constant (sync).
160 *
161 * @param {ImportApiErrorsArgument} errors The items to import.
162 */
163function importApiErrorsSync(errors) {
164 let importedErrorList;
165 if (_.isString(errors)) {
166 if (!Path.isAbsolute(errors)) {
167 errors = Path.join(process.cwd(), errors);
168 }
169 importedErrorList = JSON.parse(fs_extra_1.readFileSync(errors).toString('utf8'));
170 }
171 else if (Buffer.isBuffer(errors)) {
172 importedErrorList = JSON.parse(errors.toString('utf8'));
173 }
174 else {
175 importedErrorList = errors;
176 }
177 applyApiErrors(importedErrorList);
178}
179exports.importApiErrorsSync = importApiErrorsSync;
180/**
181 * Sends an API response.
182 *
183 * @param {Response} res The response context.
184 * @param {ApiResult} result The result context.
185 * @param {SendResponseOptions} [opts] Custom options.
186 *
187 * @return {Response} The current response context.
188 */
189function sendResponse(res, result, opts) {
190 if (_.isNil(opts)) {
191 opts = {};
192 }
193 const API_RESP = {
194 data: result.data,
195 errors: undefined,
196 success: !!result.success,
197 };
198 let code = parseInt(index_1.toStringSafe(opts.code).trim());
199 if (isNaN(code)) {
200 code = 200;
201 }
202 if (index_1.toBooleanSafe(opts.errorKeysOnly)) {
203 API_RESP.errors = index_1.asArray(result.errors).map(key => {
204 return index_1.toStringSafe(key);
205 });
206 }
207 else {
208 API_RESP.errors = index_1.asArray(result.errors).map(key => {
209 return exports.API_ERRORS[key];
210 });
211 }
212 return res.status(code)
213 .header('Content-type', 'application/json; charset=utf-8')
214 .send(Buffer.from(JSON.stringify(API_RESP), 'utf8'));
215}
216exports.sendResponse = sendResponse;
217//# sourceMappingURL=index.js.map
\No newline at end of file