opticore-webapp 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,184 +0,0 @@
1
- import process from "node:process";
2
- import chalk from 'chalk';
3
- import * as path from "path";
4
- import * as fs from "fs";
5
- import colors from "ansi-colors";
6
-
7
- import { HttpStatusCode as status } from "opticore-http-response";
8
- import { StackTraceError } from "opticore-catch-exception-error";
9
- import { Router } from "opticore-express";
10
-
11
- import { KernelModuleType } from "@webApp/domains/types/kernelModule.type";
12
- import { modulesLoadedUtils as loadedModules } from "@webApp/core/helpers/modulesLoaded.utils";
13
- import { TranslationLoader } from "opticore-translator";
14
- import { LoggerCore } from "opticore-logger";
15
-
16
-
17
-
18
- export class CoreService {
19
-
20
- /**
21
- *
22
- * @param data
23
- * @private
24
- * Return a string converted in MegaBytes
25
- */
26
- private formatMemoryUsage(data: any): string {
27
- return `${Math.round(data / 1024 / 1024 * 100) / 100} MB`;
28
- }
29
-
30
- /**
31
- * Returns an Object containing a node version, openssl, and v0
32
- */
33
- public getVersions() {
34
- const { node, openssl, v8 }: NodeJS.ProcessVersions = process.versions;
35
- const data = {
36
- "node version" : node,
37
- "openssl": openssl,
38
- "v8": v8
39
- };
40
-
41
- return {
42
- "nodeVersion" : data["node version"],
43
- "openssl": data.openssl,
44
- "v8": data.v8
45
- };
46
- }
47
-
48
- /**
49
- * Return an Object containing a Resident Set Size - total memory allocated for the process execution
50
- * Total size of the allocated heap
51
- * Actual memory used during the execution
52
- * Memory usage user
53
- * and Memory usage system
54
- */
55
- public getUsageMemory() {
56
- const memoryData: NodeJS.MemoryUsage = process.memoryUsage();
57
- const data = {
58
- "Resident Set Size - total memory allocated for the process execution": this.formatMemoryUsage(memoryData.rss),
59
- "Total size of the allocated heap": this.formatMemoryUsage(memoryData.heapTotal),
60
- "Actual memory used during the execution": this.formatMemoryUsage(memoryData.heapUsed),
61
- "V8 external memory": this.formatMemoryUsage(memoryData.external),
62
- "Memory usage user": this.formatMemoryUsage(process.cpuUsage().user),
63
- "Memory usage system": this.formatMemoryUsage(process.cpuUsage().system),
64
- }
65
-
66
- return {
67
- "rss": data["Resident Set Size - total memory allocated for the process execution"],
68
- "heapTotal": data["Total size of the allocated heap"],
69
- "heapUsed": data["Actual memory used during the execution"],
70
- "external": data["V8 external memory"],
71
- "user": data["Memory usage user"],
72
- "system": data["Memory usage system"]
73
- }
74
- }
75
-
76
- /**
77
- * Return an Object containing a project path and running server time
78
- */
79
- public getProjectInfo() {
80
- const startTime:[number, number] = process.hrtime();
81
- const endTime:[number, number] = process.hrtime(startTime);
82
- const executionTime: number = (endTime[0] * 1e9 + endTime[1]) / 1e6; // Convertir en millisecondes
83
- return {
84
- "projectPath": path.join(process.cwd()),
85
- "startingTime": `${executionTime.toFixed(5)} ms`
86
- }
87
- }
88
-
89
- /**
90
- *
91
- * @param filePath
92
- * @private
93
- */
94
- private getEnvFileLoading(filePath: string): void {
95
- const fullPath: string = path.resolve(process.cwd(), filePath);
96
- if (fs.existsSync(fullPath)) {
97
- const env: string = fs.readFileSync(fullPath, 'utf-8');
98
- const lines: string[] = env.split('\n');
99
-
100
- lines.forEach((line: string): void => {
101
- const match: RegExpMatchArray | null = line.match(/^([^#=]+)=([^#]+)$/);
102
- if (match) {
103
- const key: string = match[1].trim();
104
- process.env[key] = match[2].trim();
105
- }
106
- });
107
- }
108
- }
109
-
110
- /**
111
- *
112
- * @param development
113
- * @param production
114
- */
115
- public getServerRunningMode(development: string, production: string, ): string {
116
- /**
117
- * Load environment variables from the .env file
118
- */
119
- this.getEnvFileLoading('.env');
120
-
121
- const isDevelopment: boolean = process.env.NODE_ENV === 'development';
122
- if (isDevelopment) {
123
- return `The server is running in ${colors.bgBlue(`${colors.bold(`${development}`)}`)} mode`;
124
- } else {
125
- return `The server is running in ${colors.bgBlue(`${colors.bold(`${production}`)}`)} mode`;
126
- }
127
- }
128
-
129
- public infoServer(nodeVersion: string, startingTime: any, host: string, port: number, rss: string, heapUsed: string, user: string, system: string): void {
130
- // Padding length
131
- const paddingLength = 52;
132
-
133
- // Creating padded messages
134
- const msg0: string = ' '.padEnd(paddingLength, ' ');
135
- const msg1: string = ' [OK] Web server listening';
136
- const msg2Value: string = `${colors.bgBlue(`${colors.bold(`${nodeVersion}`)}`)}`;
137
- const msg2: string = ` The Web server is using Node.js version`;
138
- const msg3Value: string = `${colors.bgBlue(`${colors.bold(`${startingTime}`)}`)}`;
139
- const msg3: string = ` Startup time:`;
140
- const msg4: string = ` ${this.getServerRunningMode('development', 'production')}`;
141
- const msg5: string = ` ${colors.underline(`http://${host}:${port}`)}`;
142
-
143
- // display the message
144
- console.log(chalk.bgGreen.white(msg0.padEnd(paddingLength, ' ')));
145
- console.log(chalk.bgGreen.white(msg1.padEnd(paddingLength, ' ')));
146
- console.log(chalk.bgGreen.white(msg2, msg2Value.padEnd(30.5, ' ')));
147
- console.log(chalk.bgGreen.white(msg3, msg3Value.padEnd(56, ' ')));
148
- console.log(chalk.bgGreen.white(msg4.padEnd(71, ' ')));
149
- console.log(chalk.bgGreen.white(msg5.padEnd(61, ' ')));
150
- console.log(chalk.bgGreen.white(msg0.padEnd(paddingLength, ' ')));
151
- console.log(``);
152
- console.log(`${(`Resident Set Size - total memory allocated for the process execution :`)} ${colors.cyan(`${colors.bold(`${rss}`)}`)}`);
153
- console.log(`${(`Actual memory used during the execution :`)} ${colors.cyan(`${colors.bold(`${heapUsed}`)}`)}`);
154
- console.log(`${(`Memory usage by user :`)} ${colors.cyan(`${colors.bold(`${user}`)}`)}`);
155
- console.log(`${(`Memory usage by system :`)} ${colors.cyan(`${colors.bold(`${system}`)}`)}`);
156
- console.log(``);
157
- }
158
-
159
- public coreListenerEventLoaderModuleService<T extends KernelModuleType>(kernelModule: T, localeLanguage: string, loggerConfig: LoggerCore) {
160
- let router: Router[] = [];
161
- let dbCon: (() => void) | undefined;
162
-
163
- kernelModule.forEach((module): void => {
164
- if (Array.isArray(module)) {
165
- router = module as Router[];
166
- } else if (typeof module === "function") {
167
- dbCon = module as () => void;
168
- }
169
- });
170
-
171
- if (router && dbCon) {
172
- loadedModules(router, dbCon);
173
- ((): void => { dbCon(); })();
174
- } else {
175
- const stackTrace: StackTraceError = new StackTraceError(
176
- TranslationLoader.t("loadedModulesError", localeLanguage, loggerConfig),
177
- TranslationLoader.t("loadedModules", localeLanguage, loggerConfig),
178
- status.NOT_ACCEPTABLE,
179
- true
180
- );
181
- throw new Error(stackTrace.message);
182
- }
183
- }
184
- }
@@ -1,112 +0,0 @@
1
- import assert from "assert";
2
- import { CErrorName } from "opticore-catch-exception-error";
3
- import { HttpStatusCode } from "opticore-http-response";
4
- import { TranslationLoader } from "opticore-translator";
5
-
6
- export const SServerStartError = (err: any) => {
7
- switch (err.name) {
8
- case CErrorName.typeError:
9
- this.javaScriptErrors.typeError(err);
10
- break;
11
- case CErrorName.error:
12
- this.javaScriptErrors.allError(err);
13
- break;
14
- case CErrorName.evalError:
15
- this.javaScriptErrors.evalError(err);
16
- break;
17
- case CErrorName.referenceError:
18
- this.javaScriptErrors.referenceError(err);
19
- break;
20
- case CErrorName.rangeError:
21
- this.javaScriptErrors.rangeError(err);
22
- break;
23
- case CErrorName.syntaxError:
24
- this.javaScriptErrors.syntaxError(err);
25
- break;
26
- case CErrorName.uriError:
27
- this.javaScriptErrors.uRIError(err);
28
- break;
29
- case CErrorName.eacces:
30
- this.systemErrors.eAcces(err);
31
- break;
32
- case CErrorName.eaddrinuse:
33
- this.systemErrors.eAddrInUse(err);
34
- break;
35
- case CErrorName.econnrefused:
36
- this.systemErrors.eConnRefused(err);
37
- break;
38
- case CErrorName.econnreset:
39
- this.systemErrors.eConnReset(err);
40
- break;
41
- case CErrorName.eexist:
42
- this.systemErrors.eExist(err);
43
- break;
44
- case CErrorName.eisdir:
45
- this.systemErrors.eIsDir(err);
46
- break;
47
- case CErrorName.emfile:
48
- this.systemErrors.eMFile(err);
49
- break;
50
- case CErrorName.enoent:
51
- this.systemErrors.eNoEnt(err);
52
- break;
53
- case CErrorName.enotdir:
54
- this.systemErrors.eNotDir(err);
55
- break;
56
- case CErrorName.enotEmpty:
57
- this.systemErrors.eNotEmpty(err);
58
- break;
59
- case CErrorName.eperm:
60
- this.systemErrors.ePerm(err);
61
- break;
62
- case CErrorName.epipe:
63
- this.systemErrors.ePipe(err);
64
- break;
65
- case CErrorName.etimedout:
66
- this.systemErrors.eTimedOut(err);
67
- break;
68
- case CErrorName.assertionError:
69
- this.stackTrace = this.traceError(err.message, err.name, HttpStatusCode.NOT_ACCEPTABLE);
70
- err instanceof assert.AssertionError
71
- ? this.logger.error(
72
- TranslationLoader.t(this.stackTrace.name, this.localLanguage),
73
- "AssertionError",
74
- this.stackTrace.name,
75
- this.stackTrace.stack,
76
- HttpStatusCode.INTERNAL_SERVER_ERROR)
77
- : this.logger.error(
78
- TranslationLoader.t(this.stackTrace.name, this.localLanguage),
79
- "Another Error",
80
- this.stackTrace.name,
81
- this.stackTrace.stack,
82
- HttpStatusCode.INTERNAL_SERVER_ERROR);
83
- break;
84
- case CErrorName.errOsslEvpUnsupported:
85
- this.openSSLErrors.errOsSLEvpUnsupported(err);
86
- break;
87
- case CErrorName.errOsslBadDecrypt:
88
- this.openSSLErrors.errOsSLBadDecrypt(err);
89
- break;
90
- case CErrorName.errOsslWrongFinalBlockLength:
91
- this.openSSLErrors.errOsSLWrongFinalBlockLength(err);
92
- break;
93
- case CErrorName.errInvalidArgType:
94
- this.internalErrors.errInvalidArgType(err);
95
- break;
96
- case CErrorName.errInvalidCallback:
97
- this.internalErrors.errInvalidCallback(err);
98
- break;
99
- case CErrorName.errHttpHeadersSent:
100
- this.internalErrors.errHttpHeadersSent(err);
101
- break;
102
- case CErrorName.errStreamDestroyed:
103
- this.internalErrors.errStreamDestroyed(err);
104
- break;
105
- case CErrorName.errTlsCertAltnameInvalid:
106
- this.internalErrors.errTlsCertAltNameInvalid(err);
107
- break;
108
- case CErrorName.errUnsupportedEsmUrlScheme:
109
- this.internalErrors.errUnsupportedEsmUrlScheme(err);
110
- break;
111
- }
112
- }
File without changes
File without changes
@@ -1,112 +0,0 @@
1
- import process from 'node:process';
2
- import EventEmitter from "node:events";
3
- import { express, NextFunction } from "opticore-express";
4
- import {
5
- ServerListenEventError,
6
- CEventNameError as eventName,
7
- CEvent as event
8
- } from "opticore-catch-exception-error";
9
-
10
-
11
-
12
- /**
13
- *
14
- */
15
- export function eventProcessHandler(localeLanguage: string): void {
16
- const errorEmitter = new EventEmitter();
17
- const app = express();
18
- const serverListenEvent: ServerListenEventError = new ServerListenEventError(localeLanguage);
19
-
20
- /**
21
- * Listener for error events
22
- */
23
- errorEmitter.on(eventName.error, (error: Error): void => {
24
- serverListenEvent.listenerError(error);
25
- });
26
-
27
- /**
28
- * Catch uncaught exceptions
29
- * Process event listeners
30
- */
31
- process.on(event.beforeExit, (code: number): void => {
32
- setTimeout((): void => {
33
- serverListenEvent.processBeforeExit(code);
34
- }, 100);
35
- });
36
-
37
- /**
38
- *
39
- */
40
- process.on(event.disconnect, (): void => {
41
- serverListenEvent.processDisconnected();
42
- });
43
-
44
- /**
45
- *
46
- */
47
- process.on(event.exit, (code: number): void => {
48
- serverListenEvent.exited(code);
49
- });
50
-
51
- /**
52
- *
53
- */
54
- process.on(event.rejectionHandled, (promise: Promise<any>): void => {
55
- serverListenEvent.promiseRejectionHandled(promise);
56
- });
57
-
58
- /**
59
- *
60
- */
61
- process.on(event.uncaughtException, (error: any): void => {
62
- serverListenEvent.uncaughtException(error);
63
- });
64
-
65
- /**
66
- *
67
- */
68
- process.on(event.uncaughtExceptionMonitor, (error: any): void => {
69
- serverListenEvent.uncaughtExceptionMonitor(error);
70
- });
71
-
72
- /**
73
- *
74
- */
75
- process.on(event.unhandledRejection, (reason: any, promise: Promise<any>): void => {
76
- serverListenEvent.unhandledRejection(reason, promise);
77
- });
78
-
79
- /**
80
- *
81
- */
82
- process.on(event.warning, (warning: any): void => {
83
- serverListenEvent.warning(warning);
84
- });
85
- process.on(event.message, (message: any): void => {
86
- serverListenEvent.message(message);
87
- });
88
-
89
- /**
90
- *
91
- */
92
- process.on(event.multipleResolves, (type: string, promise: Promise<any>, reason: any): void => {
93
- serverListenEvent.multipleResolves(type, promise, reason);
94
- });
95
-
96
- /**
97
- * Handle specific signals
98
- */
99
- process.on(event.sigint, (): void => {
100
- serverListenEvent.processInterrupted();
101
- });
102
- process.on(event.sigterm, (signal: any): void => {
103
- serverListenEvent.sigtermSignalReceived(signal);
104
- });
105
-
106
- /**
107
- * Express error-handling middleware
108
- */
109
- app.use((err: Error, req: Request, res: Response, next: NextFunction): void => {
110
- serverListenEvent.expressErrorHandlingMiddleware(errorEmitter, err, req, res, next);
111
- });
112
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * Give time like: 6-8-2024 4:30:29
3
- */
4
-
5
-
6
- export const dateTimeFormattedUtils: string = `${(new Date().getMonth())}-${(new Date().getDate())}-${(new Date().getFullYear())} ${(new Date().getHours())}:${(new Date().getMinutes())}:${(new Date().getSeconds())}`;
@@ -1,20 +0,0 @@
1
- import colors from "ansi-colors";
2
- import { dateTimeFormattedUtils } from "@webApp/core/helpers/dateTimeFormatted.utils";
3
-
4
- export class LogMessageUtils {
5
- static success(title: string, action: string, contentAction: string): void {
6
- console.log(`${colors.green(`✔`)} ${colors.bgGreen(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} ${dateTimeFormattedUtils} | ${colors.bgGreen(`${colors.white(` Success `)}`)} [ ${action} ] ${contentAction} - [ Status ] ${colors.bgGreen(`${colors.white(` 200 `)}`)}`);
7
- }
8
- static warning(title: string, action: string, contentAction: string): void {
9
- console.warn(`${colors.yellow(`⚠️`)} ${colors.bgYellow(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} ${dateTimeFormattedUtils} | ${colors.bgYellow(`${colors.white(` Warning `)}`)} ${contentAction}`);
10
- }
11
- static info(title: string, action: string, contentAction: string): void {
12
- console.info(`${colors.cyan(`ⓘ`)} ${colors.bgCyan(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} ${dateTimeFormattedUtils} | ${colors.bgCyan(`${colors.white(` Info `)}`)} ${contentAction}`);
13
- }
14
- static error(title: string, errorType: any, stackTrace: any, messageContent: any, httpCodeValue: number): void {
15
- console.error(`${colors.red(`✘`)} ${colors.bgRed(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} | ${dateTimeFormattedUtils} | [ ${colors.red(`${colors.bold(` ${errorType} `)}`)} ] | [ ${colors.bold(`stack trace`)} ] ${colors.red(`${stackTrace}`)} - ${colors.red(`${messageContent}`)} - [ ${colors.red(`${colors.bold(` HttpCode `)}`)} ] ${colors.red(`${colors.bold(` ${httpCodeValue} `)}`)} `);
16
- }
17
- static requestError(title: string, errorName: string, errorMessage: string, errorCode: number): void {
18
- console.error(`[ ${colors.red(`${title}`)} ] ${dateTimeFormattedUtils} | ${colors.bgRed(`${colors.white(` ERROR `)}`)} ${colors.red(`[ ${errorName} ]`)} ${colors.red(`${errorMessage}`)} - [ Status ] ${colors.bgRed(`${colors.white(` ${errorCode} `)}`)}`);
19
- }
20
- }
@@ -1,23 +0,0 @@
1
- import colors from "ansi-colors";
2
- import { Router } from "opticore-express";
3
- import { LogMessageUtils } from "@webApp/core/helpers/logMessage.utils";
4
- import { dateTimeFormattedUtils } from "@webApp/core/helpers/dateTimeFormatted.utils";
5
- import { TranslationLoader } from "opticore-translator";
6
- import { LoggerCore } from "opticore-logger";
7
-
8
-
9
-
10
- export function modulesLoadedUtils(allAppRoutes: Router[], dbConChecker: () => void, localeLanguage: string): void {
11
- LogMessageUtils.success(
12
- `${TranslationLoader.t("kernel", localeLanguage)}`,
13
- `${TranslationLoader.t("loadKernel", localeLanguage)}`,
14
- `${TranslationLoader.t("moduleAppLoaded", localeLanguage)}`
15
- );
16
- console.log(`${colors.whiteBright(` ${TranslationLoader.t("content", localeLanguage)}`)} ${colors.green(`${TranslationLoader.t("kernel", localeLanguage)} :`)} ${colors.cyan(`${colors.bold(`${TranslationLoader.t("serverSide", localeLanguage)}`)}`)} ${TranslationLoader.t("hasBeenLoadedSuccessfully", localeLanguage)} ${colors.green(`✔`)}`);
17
- allAppRoutes
18
- ? console.log(`${colors.whiteBright(` ${TranslationLoader.t("content", localeLanguage)}`)} ${colors.green(`${TranslationLoader.t("kernel", localeLanguage)} :`)} ${colors.cyan(`${colors.bold(`${TranslationLoader.t("routerService", localeLanguage)}`)} `)} ${colors.green(`✔`)}`)
19
- : console.log(`${colors.red(`✘`)} ${colors.bgRed(` ${colors.bold(`${colors.white(` ${TranslationLoader.t("registerRoutes", localeLanguage)} `)}`)} `)} | ${dateTimeFormattedUtils} | [ ${colors.red(`${colors.bold(` ${TranslationLoader.t("fail", localeLanguage)} `)}`)} ] | [ ${colors.bold(` ${TranslationLoader.t("loading", localeLanguage)} `)} ] - ${colors.red(` ${TranslationLoader.t("routers", localeLanguage)} `)} - ${TranslationLoader.t("registerLoadingFailed", localeLanguage)} `);
20
- typeof dbConChecker == "function"
21
- ? console.log(`${colors.whiteBright(` ${TranslationLoader.t("content", localeLanguage)}`)} ${colors.green(`${TranslationLoader.t("kernel", localeLanguage)} :`)} ${colors.cyan(`${colors.bold(`${TranslationLoader.t("dbConnChecker", localeLanguage)}`)}`)} ${TranslationLoader.t("hasBeenLoadedSuccessfully", localeLanguage)} ${colors.green(`✔`)}`)
22
- : "";
23
- }
@@ -1,154 +0,0 @@
1
- import * as path from "path";
2
- import { createRequire } from "module";
3
- import corsOrigin, { CorsOptions } from "cors";
4
- import { Server as serverWebApp } from "http";
5
- import { IncomingMessage, ServerResponse } from "node:http";
6
-
7
- import {
8
- CEventNameError as eventName,
9
- ServerListenEventError,
10
- CErrorName,
11
- JavaScriptErrors,
12
- InternalErrors,
13
- AssertionErrors,
14
- OpenSSLErrors,
15
- SystemErrors,
16
- StackTraceError,
17
- } from "opticore-catch-exception-error";
18
- import { express } from "opticore-express";
19
- import { getEnvironnementValue } from "opticore-env-access";
20
- import { TranslationLoader } from "opticore-translator";
21
- import { LoggerCore } from "opticore-logger";
22
-
23
- import { IRouteDefinition } from "@webApp/domains/interfaces/routeDefinition.interface";
24
- import { eventProcessHandler } from "@webApp/core/handlers/eventProcess.handler";
25
- import { CoreService } from "@webApp/application/service/core.service";
26
- import { dateTimeFormattedUtils as currentDate } from "@webApp/core/helpers/dateTimeFormatted.utils";
27
- import { SServerStartError } from "@webApp/application/service/serverStartError.service";
28
- import {requestCallsEvent} from "opticore-request-call-event";
29
-
30
-
31
- export class WebServerCore {
32
- private serverUtility: CoreService = new CoreService();
33
- private expressApp = express();
34
-
35
- private readonly localLanguage: string;
36
- private readonly loggerConfig: LoggerCore;
37
- private readonly routerExpressApp: express.Application;
38
- private readonly getEnvironnement: any;
39
- private readonly environnementPath: string;
40
-
41
- private serverListenEvent: ServerListenEventError;
42
- private javaScriptErrors: JavaScriptErrors;
43
- private internalErrors: InternalErrors;
44
- private assertionErrors: AssertionErrors;
45
- private openSSLErrors: OpenSSLErrors;
46
- private systemErrors: SystemErrors;
47
-
48
-
49
- constructor(app: express.Application, loggerConfig: LoggerCore, localLanguage: string, environnementPath: any, corsOriginOptions?: Partial<CorsOptions>) {
50
- this.getEnvironnement = getEnvironnementValue(environnementPath);
51
-
52
- this.routerExpressApp = app;
53
- this.loggerConfig = loggerConfig;
54
- this.localLanguage = localLanguage;
55
- this.environnementPath = environnementPath;
56
-
57
- this.expressApp.use(express.json());
58
- this.expressApp.use(express.raw());
59
- this.expressApp.use(express.text());
60
- this.expressApp.use(express.urlencoded({ extended: true }));
61
- this.expressApp.use(corsOrigin(corsOriginOptions));
62
-
63
- this.serverListenEvent = new ServerListenEventError(localLanguage);
64
- this.javaScriptErrors = new JavaScriptErrors(localLanguage);
65
- this.assertionErrors = new AssertionErrors(localLanguage);
66
- this.internalErrors = new InternalErrors(localLanguage);
67
- this.openSSLErrors = new OpenSSLErrors(localLanguage);
68
- this.systemErrors = new SystemErrors(localLanguage);
69
-
70
- this.stackTraceErrorHandling(localLanguage);
71
- this.translationWebAppLoader();
72
- }
73
-
74
-
75
- public onStartServer(routers: { featureRoute: IRouteDefinition[] }[]) {
76
- return this.expressApp.listen(
77
- this.getEnvironnement.appHost,
78
- this.getEnvironnement.appPort,
79
- (): void => {
80
- try {
81
- if (this.getEnvironnement.appHost === "" && this.getEnvironnement.appPort === 0) {
82
- this.serverListenEvent.hostPortUndefined(this.getEnvironnement.appPort);
83
- } else if (this.getEnvironnement.appHost === "") {
84
- this.serverListenEvent.hostUndefined(this.getEnvironnement.appHost);
85
- } else if (this.getEnvironnement.appPort === 0) {
86
- this.serverListenEvent.portUndefined();
87
- } else {
88
- this.registerRoutes(routers);
89
- }
90
- } catch (err: any) {
91
- SServerStartError(err);
92
- }
93
- }
94
- );
95
- }
96
-
97
- //, kernelModule: KernelModuleType
98
- public onListeningOnServerEvent(serverWeb: serverWebApp, localLanguage: string): void {
99
- serverWeb.on(eventName.error, (err: Error): void => {
100
- this.serverListenEvent.onEventError(err);
101
- }).on(eventName.close, (): void => {
102
- this.serverListenEvent.serverClosing();
103
- }).on(eventName.drop, (): void => {
104
- this.serverListenEvent.dropNewConnection();
105
- }).on(eventName.listening, (): void => {
106
- this.infoWebApp();
107
- //this.serverUtility.coreListenerEventLoaderModuleService(kernelModule);
108
- });
109
- }
110
-
111
- public onRequestOnServerEvent(serverWeb: serverWebApp): void {
112
- serverWeb.on(eventName.request, (req: IncomingMessage, res: ServerResponse): void => {
113
- requestCallsEvent(
114
- req,
115
- res,
116
- this.getEnvironnement.appHost,
117
- this.getEnvironnement.appPort,
118
- currentDate,
119
- this.environnementPath,
120
- this.localLanguage
121
- );
122
- });
123
- }
124
-
125
- private translationWebAppLoader(): void {
126
- const require: NodeJS.Require = createRequire(import.meta.url);
127
- const packagePath: string = path.dirname(require.resolve("opticore-webapp"));
128
-
129
- const translateMsgJsonFilePath: string = path.join(packagePath, "utils", "translations");
130
- TranslationLoader.loadTranslations(translateMsgJsonFilePath);
131
- }
132
- private registerRoutes(allFeatureRoutes: { featureRoute: IRouteDefinition[] }[]): void {
133
- allFeatureRoutes.map((router: {featureRoute: IRouteDefinition[]} ): void => {
134
- router.featureRoute.map((route: IRouteDefinition): void => {
135
- this.expressApp.use(route.path, route.handler);
136
- });
137
- });
138
- }
139
- private stackTraceErrorHandling(localLanguage: string): void {
140
- eventProcessHandler(localLanguage);
141
- }
142
- private infoWebApp(): void {
143
- this.serverUtility.infoServer(
144
- this.serverUtility.getVersions().nodeVersion,
145
- this.serverUtility.getProjectInfo().startingTime,
146
- this.getEnvironnement.appHost,
147
- Number(this.getEnvironnement.appPort),
148
- this.serverUtility.getUsageMemory().rss,
149
- this.serverUtility.getUsageMemory().heapUsed,
150
- this.serverUtility.getUsageMemory().user,
151
- this.serverUtility.getUsageMemory().system
152
- );
153
- }
154
- }
@@ -1,6 +0,0 @@
1
- import { Router } from "opticore-express";
2
-
3
- export interface IRouteDefinition {
4
- path: string;
5
- handler: Router;
6
- }
@@ -1,3 +0,0 @@
1
- import { IRouteDefinition } from "@webApp/domains/interfaces/routeDefinition.interface";
2
-
3
- export type KernelModuleType = [{ featureRoute: IRouteDefinition[] }[], () => void];
package/src/index.ts DELETED
@@ -1,11 +0,0 @@
1
- import { WebServerCore as WebServer } from "@webApp/core/webServer.core";
2
-
3
-
4
- import { type IRouteDefinition } from "@webApp/domains/interfaces/routeDefinition.interface";
5
- import { type KernelModuleType } from "@webApp/domains/types/kernelModule.type";
6
-
7
- export {
8
- IRouteDefinition,
9
- KernelModuleType,
10
- WebServer,
11
- }