emilsoftware-utilities 1.1.0 → 1.1.2

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.
package/.idea/.name ADDED
@@ -0,0 +1 @@
1
+ emilsoftware-utilities
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="WEB_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/.tmp" />
6
+ <excludeFolder url="file://$MODULE_DIR$/temp" />
7
+ <excludeFolder url="file://$MODULE_DIR$/tmp" />
8
+ </content>
9
+ <orderEntry type="inheritedJdk" />
10
+ <orderEntry type="sourceFolder" forTests="false" />
11
+ </component>
12
+ </module>
@@ -0,0 +1,10 @@
1
+ <component name="InspectionProjectProfileManager">
2
+ <profile version="1.0">
3
+ <option name="myName" value="Project Default" />
4
+ <inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
5
+ <Languages>
6
+ <language minSize="63" name="TypeScript" />
7
+ </Languages>
8
+ </inspection_tool>
9
+ </profile>
10
+ </component>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/emilsoftware-utilities.iml" filepath="$PROJECT_DIR$/.idea/emilsoftware-utilities.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
package/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
package/autobind.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Return a descriptor removing the value and returning a getter
3
+ * The getter will return a .bind version of the function
4
+ * and memoize the result against a symbol on the instance
5
+ */
6
+ export declare function boundMethod(target: any, key: any, descriptor: any): {
7
+ configurable: boolean;
8
+ get(): any;
9
+ set(value: any): void;
10
+ };
11
+ /**
12
+ * Use boundMethod to bind all methods on the target.prototype
13
+ */
14
+ export declare function boundClass(target: any): any;
15
+ export default function autobind(...args: any[]): any;
package/autobind.js ADDED
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ // DECORATOR
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.boundClass = exports.boundMethod = void 0;
5
+ /**
6
+ * Return a descriptor removing the value and returning a getter
7
+ * The getter will return a .bind version of the function
8
+ * and memoize the result against a symbol on the instance
9
+ */
10
+ function boundMethod(target, key, descriptor) {
11
+ var fn = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
12
+ if (typeof fn !== 'function') {
13
+ throw new TypeError("@boundMethod decorator can only be applied to methods not: ".concat(typeof fn));
14
+ }
15
+ // In IE11 calling Object.defineProperty has a side effect of evaluating the
16
+ // getter for the property which is being replaced. This causes infinite
17
+ // recursion and an "Out of stack space" error.
18
+ var definingProperty = false;
19
+ return {
20
+ configurable: true,
21
+ get: function () {
22
+ // eslint-disable-next-line no-prototype-builtins
23
+ if (definingProperty || this === target.prototype || this.hasOwnProperty(key) ||
24
+ typeof fn !== 'function') {
25
+ return fn;
26
+ }
27
+ var boundFn = fn.bind(this);
28
+ definingProperty = true;
29
+ if (key) {
30
+ Object.defineProperty(this, key, {
31
+ configurable: true,
32
+ get: function () {
33
+ return boundFn;
34
+ },
35
+ set: function (value) {
36
+ fn = value;
37
+ // @ts-ignore
38
+ delete this[key];
39
+ }
40
+ });
41
+ }
42
+ definingProperty = false;
43
+ return boundFn;
44
+ },
45
+ set: function (value) {
46
+ fn = value;
47
+ }
48
+ };
49
+ }
50
+ exports.boundMethod = boundMethod;
51
+ /**
52
+ * Use boundMethod to bind all methods on the target.prototype
53
+ */
54
+ function boundClass(target) {
55
+ // (Using reflect to get all keys including symbols)
56
+ var keys;
57
+ // Use Reflect if exists
58
+ if (typeof Reflect !== 'undefined' && typeof Reflect.ownKeys === 'function') {
59
+ keys = Reflect.ownKeys(target.prototype);
60
+ }
61
+ else {
62
+ keys = Object.getOwnPropertyNames(target.prototype);
63
+ // Use symbols if support is provided
64
+ if (typeof Object.getOwnPropertySymbols === 'function') {
65
+ // @ts-ignore
66
+ keys = keys.concat(Object.getOwnPropertySymbols(target.prototype));
67
+ }
68
+ }
69
+ keys.forEach(function (key) {
70
+ // Ignore special case target method
71
+ if (key === 'constructor') {
72
+ return;
73
+ }
74
+ var descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
75
+ // Only methods need binding
76
+ if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.value) === 'function') {
77
+ Object.defineProperty(target.prototype, key, boundMethod(target, key, descriptor));
78
+ }
79
+ });
80
+ return target;
81
+ }
82
+ exports.boundClass = boundClass;
83
+ function autobind() {
84
+ var args = [];
85
+ for (var _i = 0; _i < arguments.length; _i++) {
86
+ args[_i] = arguments[_i];
87
+ }
88
+ if (args.length === 1) {
89
+ // @ts-ignore
90
+ return boundClass.apply(void 0, args);
91
+ }
92
+ // @ts-ignore
93
+ return boundMethod.apply(void 0, args);
94
+ }
95
+ exports.default = autobind;
package/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import autobind from "./autobind";
2
+ import logExecutionTime from "./log-execution-time";
3
+ import { Logger, LogLevels } from "./logger";
4
+ import { Orm } from "./orm";
5
+ import { Utilities } from "./utilities";
6
+ export { autobind, logExecutionTime, Logger, LogLevels, Orm, Utilities };
@@ -0,0 +1 @@
1
+ export default function logExecutionTime(fileName?: string): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ // DECORATOR
40
+ var logger_1 = require("./logger");
41
+ function logExecutionTime(fileName) {
42
+ if (fileName === void 0) { fileName = ""; }
43
+ return function (target, propertyKey, descriptor) {
44
+ var logger = new logger_1.Logger(fileName);
45
+ var originalMethod = descriptor.value;
46
+ descriptor.value = function () {
47
+ var args = [];
48
+ for (var _i = 0; _i < arguments.length; _i++) {
49
+ args[_i] = arguments[_i];
50
+ }
51
+ return __awaiter(this, void 0, void 0, function () {
52
+ var start, result, end, durationInMilliseconds, error_1;
53
+ return __generator(this, function (_a) {
54
+ switch (_a.label) {
55
+ case 0:
56
+ start = process.hrtime();
57
+ logger.info(" ".concat(propertyKey, " method execution started . . ."));
58
+ _a.label = 1;
59
+ case 1:
60
+ _a.trys.push([1, 3, , 4]);
61
+ return [4 /*yield*/, originalMethod.apply(this, args)];
62
+ case 2:
63
+ result = _a.sent();
64
+ end = process.hrtime(start);
65
+ durationInMilliseconds = end[0] * 1000 + end[1] / 1e6;
66
+ logger.info(" ".concat(propertyKey, " method took ").concat(durationInMilliseconds.toFixed(2), " ms to execute"));
67
+ return [2 /*return*/, result];
68
+ case 3:
69
+ error_1 = _a.sent();
70
+ throw error_1;
71
+ case 4: return [2 /*return*/];
72
+ }
73
+ });
74
+ });
75
+ };
76
+ return descriptor;
77
+ };
78
+ }
79
+ exports.default = logExecutionTime;
package/logger.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export declare enum LogLevels {
2
+ INFO = "INFO",
3
+ ERROR = "ERROR",
4
+ DEBUG = "DEBUG",
5
+ LOG = "LOG"
6
+ }
7
+ export declare class Logger {
8
+ private readonly winstonLogger;
9
+ tag: string;
10
+ private logFormat;
11
+ constructor(tag: string);
12
+ private getFileName;
13
+ execStart(prefix?: string): any;
14
+ execStop(prefix: string, startTime: any, error?: boolean): any;
15
+ info(...data: any): void;
16
+ debug(...data: any): void;
17
+ log(...data: any): void;
18
+ error(...data: any): void;
19
+ private print;
20
+ }
package/logger.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
26
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
27
+ if (ar || !(i in from)) {
28
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
29
+ ar[i] = from[i];
30
+ }
31
+ }
32
+ return to.concat(ar || Array.prototype.slice.call(from));
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.Logger = exports.LogLevels = void 0;
39
+ var winston_1 = __importDefault(require("winston"));
40
+ var path = __importStar(require("path"));
41
+ var fs = __importStar(require("fs"));
42
+ var LogLevels;
43
+ (function (LogLevels) {
44
+ LogLevels["INFO"] = "INFO";
45
+ LogLevels["ERROR"] = "ERROR";
46
+ LogLevels["DEBUG"] = "DEBUG";
47
+ LogLevels["LOG"] = "LOG";
48
+ })(LogLevels || (exports.LogLevels = LogLevels = {}));
49
+ var Logger = /** @class */ (function () {
50
+ function Logger(tag) {
51
+ this.tag = "[UNTAGGED]";
52
+ this.logFormat = winston_1.default.format.printf(function (tmp) {
53
+ var time = tmp.time, file = tmp.file, level = tmp.level, message = tmp.message;
54
+ return "".concat(JSON.stringify({ time: time, file: file === null || file === void 0 ? void 0 : file.replaceAll("\\", "/"), level: level, message: message }), ",");
55
+ });
56
+ var fileName = this.getFileName();
57
+ var logsDirectory = "logs";
58
+ var logFilePath = path.join(logsDirectory, fileName + ".json");
59
+ if (!fs.existsSync(logsDirectory)) {
60
+ fs.mkdirSync(logsDirectory);
61
+ }
62
+ this.tag = tag;
63
+ this.winstonLogger = winston_1.default.createLogger({
64
+ format: winston_1.default.format.json(),
65
+ transports: [new winston_1.default.transports.File({ filename: logFilePath, format: this.logFormat })],
66
+ });
67
+ }
68
+ Logger.prototype.getFileName = function () {
69
+ var now = new Date();
70
+ return now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
71
+ };
72
+ Logger.prototype.execStart = function (prefix) {
73
+ if (prefix === void 0) { prefix = ""; }
74
+ this.print(LogLevels.INFO, "".concat(prefix, " - Execution started"));
75
+ return performance.now();
76
+ };
77
+ Logger.prototype.execStop = function (prefix, startTime, error) {
78
+ if (prefix === void 0) { prefix = ""; }
79
+ if (error === void 0) { error = false; }
80
+ switch (error) {
81
+ case true: {
82
+ this.print(LogLevels.ERROR, "".concat(prefix, " - Execution ended due to an error. Execution time: ").concat(performance.now() - startTime, " ms"));
83
+ break;
84
+ }
85
+ case false: {
86
+ this.print(LogLevels.INFO, "".concat(prefix, " - Execution ended successfully. Execution time: ").concat(performance.now() - startTime, " ms"));
87
+ break;
88
+ }
89
+ }
90
+ };
91
+ Logger.prototype.info = function () {
92
+ var data = [];
93
+ for (var _i = 0; _i < arguments.length; _i++) {
94
+ data[_i] = arguments[_i];
95
+ }
96
+ this.print.apply(this, __spreadArray([LogLevels.INFO], data, false));
97
+ };
98
+ Logger.prototype.debug = function () {
99
+ var data = [];
100
+ for (var _i = 0; _i < arguments.length; _i++) {
101
+ data[_i] = arguments[_i];
102
+ }
103
+ this.print.apply(this, __spreadArray([LogLevels.DEBUG], data, false));
104
+ };
105
+ Logger.prototype.log = function () {
106
+ var data = [];
107
+ for (var _i = 0; _i < arguments.length; _i++) {
108
+ data[_i] = arguments[_i];
109
+ }
110
+ this.print.apply(this, __spreadArray([LogLevels.LOG], data, false));
111
+ };
112
+ Logger.prototype.error = function () {
113
+ var data = [];
114
+ for (var _i = 0; _i < arguments.length; _i++) {
115
+ data[_i] = arguments[_i];
116
+ }
117
+ this.print.apply(this, __spreadArray([LogLevels.ERROR], data, false));
118
+ };
119
+ Logger.prototype.print = function (level) {
120
+ var _a;
121
+ if (level === void 0) { level = LogLevels.INFO; }
122
+ var data = [];
123
+ for (var _i = 1; _i < arguments.length; _i++) {
124
+ data[_i - 1] = arguments[_i];
125
+ }
126
+ var now = new Date();
127
+ // Utilities.getNowDateString();
128
+ this.winstonLogger.defaultMeta = {
129
+ file: this.tag, time: now,
130
+ level: level
131
+ };
132
+ (_a = this.winstonLogger)[level.toLowerCase()].apply(_a, data);
133
+ // @ts-ignore
134
+ console[level.toLowerCase()].apply(console, __spreadArray(["[".concat(level, "][").concat(now, "][").concat(this.tag.split("\\").pop(), "]")], data, false));
135
+ };
136
+ return Logger;
137
+ }());
138
+ exports.Logger = Logger;
package/orm.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { Database, Options, Transaction } from "node-firebird";
2
+ interface Orm {
3
+ quote: (value: string) => string;
4
+ testConnection: (options: Options) => Promise<any>;
5
+ query: (options: Options, query: any, parameters?: any[]) => Promise<any>;
6
+ execute: (options: Options, query: any, parameters?: any[]) => Promise<any>;
7
+ trimParam: (param: any) => string;
8
+ connect: (options: Options) => Promise<any>;
9
+ startTransaction: (db: Database) => Promise<any>;
10
+ executeQueries: (transaction: Transaction, queries: string[], params: any[]) => any;
11
+ commitTransaction: (transaction: Transaction) => Promise<any>;
12
+ }
13
+ export declare const Orm: Orm;
14
+ export {};
package/orm.js ADDED
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.Orm = void 0;
27
+ // @ts-ignore
28
+ var Firebird = __importStar(require("es-node-firebird"));
29
+ var logger_1 = require("./logger");
30
+ var quote = function (value) {
31
+ return "\"" + value + "\"";
32
+ };
33
+ var testConnection = function (options) {
34
+ var logger = new logger_1.Logger(__filename);
35
+ return new Promise(function (resolve) {
36
+ Firebird.attach(options, function (err, db) {
37
+ if (err) {
38
+ logger.error("La connessione con il DATABASE non è andata a buon fine.");
39
+ return resolve(false);
40
+ }
41
+ logger.info("DATABASE connesso.");
42
+ return resolve(true);
43
+ });
44
+ });
45
+ };
46
+ var query = function (options, query, parameters) {
47
+ if (parameters === void 0) { parameters = []; }
48
+ return new Promise(function (resolve, reject) {
49
+ Firebird.attach(options, function (err, db) {
50
+ if (err) {
51
+ return reject(err);
52
+ }
53
+ db.query(query, parameters, function (error, result) {
54
+ if (error) {
55
+ db.detach();
56
+ return reject(error);
57
+ }
58
+ db.detach();
59
+ return resolve(result);
60
+ });
61
+ });
62
+ });
63
+ };
64
+ var execute = function (options, query, parameters) {
65
+ if (parameters === void 0) { parameters = []; }
66
+ return new Promise(function (resolve, reject) {
67
+ Firebird.attach(options, function (err, db) {
68
+ if (err) {
69
+ return reject(err);
70
+ }
71
+ db.execute(query, parameters, function (error, result) {
72
+ if (error) {
73
+ db.detach();
74
+ return reject(error);
75
+ }
76
+ db.detach();
77
+ return resolve(result);
78
+ });
79
+ });
80
+ });
81
+ };
82
+ var trimParam = function (param) {
83
+ if (typeof param === "string" || param instanceof String) {
84
+ return param.trim();
85
+ }
86
+ return param;
87
+ };
88
+ var connect = function (options) {
89
+ return new Promise(function (resolve, reject) {
90
+ Firebird.attach(options, function (err, db) {
91
+ if (err)
92
+ return reject(err);
93
+ else
94
+ return resolve(db);
95
+ });
96
+ });
97
+ };
98
+ var startTransaction = function (db) {
99
+ return new Promise(function (resolve, reject) {
100
+ db.transaction(Firebird.ISOLATION_READ_COMMITTED, function (err, transaction) {
101
+ if (err)
102
+ return reject(err);
103
+ else
104
+ return resolve(transaction);
105
+ });
106
+ });
107
+ };
108
+ var executeQueries = function (transaction, queries, params) {
109
+ return queries.reduce(function (promiseChain, currentQuery, index) {
110
+ return promiseChain.then(function () { return new Promise(function (resolve, reject) {
111
+ transaction.query(currentQuery, params[index], function (err, result) {
112
+ if (err)
113
+ return reject(err);
114
+ else
115
+ return resolve(result);
116
+ });
117
+ }); });
118
+ }, Promise.resolve());
119
+ };
120
+ var commitTransaction = function (transaction) {
121
+ return new Promise(function (resolve, reject) {
122
+ transaction.commit(function (err) {
123
+ if (err)
124
+ return reject(err);
125
+ else
126
+ return resolve('Transaction committed successfully.');
127
+ });
128
+ });
129
+ };
130
+ exports.Orm = {
131
+ quote: quote,
132
+ testConnection: testConnection,
133
+ query: query,
134
+ execute: execute,
135
+ trimParam: trimParam,
136
+ connect: connect,
137
+ startTransaction: startTransaction,
138
+ executeQueries: executeQueries,
139
+ commitTransaction: commitTransaction
140
+ };
package/package.json CHANGED
@@ -1,11 +1,8 @@
1
1
  {
2
2
  "name": "emilsoftware-utilities",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "Utilities for EmilSoftware",
5
5
  "main": "index.js",
6
- "files": [
7
- "dist"
8
- ],
9
6
  "scripts": {
10
7
  "test": "echo \"Error: no test specified\" && exit 1",
11
8
  "build": "tsc",
@@ -26,6 +23,7 @@
26
23
  "winston": "^3.11.0"
27
24
  },
28
25
  "devDependencies": {
26
+ "@types/express": "^4.17.21",
29
27
  "@types/node": "^20.10.5",
30
28
  "typescript": "^5.3.3"
31
29
  }
@@ -0,0 +1,94 @@
1
+ // DECORATOR
2
+
3
+ /**
4
+ * Return a descriptor removing the value and returning a getter
5
+ * The getter will return a .bind version of the function
6
+ * and memoize the result against a symbol on the instance
7
+ */
8
+ export function boundMethod(target:any, key: any, descriptor: any) {
9
+ let fn = descriptor?.value;
10
+
11
+ if (typeof fn !== 'function') {
12
+ throw new TypeError(`@boundMethod decorator can only be applied to methods not: ${typeof fn}`);
13
+ }
14
+
15
+ // In IE11 calling Object.defineProperty has a side effect of evaluating the
16
+ // getter for the property which is being replaced. This causes infinite
17
+ // recursion and an "Out of stack space" error.
18
+ let definingProperty = false;
19
+
20
+ return {
21
+ configurable: true,
22
+ get() {
23
+ // eslint-disable-next-line no-prototype-builtins
24
+ if (definingProperty || this === target.prototype || this.hasOwnProperty(key as string | number | symbol) ||
25
+ typeof fn !== 'function') {
26
+ return fn;
27
+ }
28
+
29
+ const boundFn = fn.bind(this);
30
+ definingProperty = true;
31
+ if (key) {
32
+ Object.defineProperty(this, key, {
33
+ configurable: true,
34
+ get() {
35
+ return boundFn;
36
+ },
37
+ set(value) {
38
+ fn = value;
39
+ // @ts-ignore
40
+ delete this[key];
41
+ }
42
+ });
43
+ }
44
+ definingProperty = false;
45
+ return boundFn;
46
+ },
47
+ set(value: any) {
48
+ fn = value;
49
+ }
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Use boundMethod to bind all methods on the target.prototype
55
+ */
56
+ export function boundClass(target: any) {
57
+ // (Using reflect to get all keys including symbols)
58
+ let keys;
59
+ // Use Reflect if exists
60
+ if (typeof Reflect !== 'undefined' && typeof Reflect.ownKeys === 'function') {
61
+ keys = Reflect.ownKeys(target.prototype);
62
+ } else {
63
+ keys = Object.getOwnPropertyNames(target.prototype);
64
+ // Use symbols if support is provided
65
+ if (typeof Object.getOwnPropertySymbols === 'function') {
66
+ // @ts-ignore
67
+ keys = keys.concat(Object.getOwnPropertySymbols(target.prototype));
68
+ }
69
+ }
70
+
71
+ keys.forEach(key => {
72
+ // Ignore special case target method
73
+ if (key === 'constructor') {
74
+ return;
75
+ }
76
+
77
+ const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
78
+
79
+ // Only methods need binding
80
+ if (typeof descriptor?.value === 'function') {
81
+ Object.defineProperty(target.prototype, key, boundMethod(target, key, descriptor));
82
+ }
83
+ });
84
+ return target;
85
+ }
86
+
87
+ export default function autobind(...args: any[]) {
88
+ if (args.length === 1) {
89
+ // @ts-ignore
90
+ return boundClass(...args);
91
+ }
92
+ // @ts-ignore
93
+ return boundMethod(...args);
94
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ import autobind from "./autobind"
2
+ import logExecutionTime from "./log-execution-time"
3
+ import {Logger, LogLevels} from "./logger";
4
+ import {Orm} from "./orm";
5
+ import {Utilities} from "./utilities";
6
+ export {autobind, logExecutionTime, Logger, LogLevels, Orm, Utilities};
@@ -0,0 +1,25 @@
1
+ // DECORATOR
2
+ import {Logger} from "./logger";
3
+
4
+ export default function logExecutionTime(fileName: string = "") {
5
+ return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
6
+ const logger: Logger = new Logger(fileName);
7
+ const originalMethod = descriptor.value;
8
+ descriptor.value = async function (...args: any[]) {
9
+ const start = process.hrtime();
10
+ logger.info(` ${propertyKey} method execution started . . .`);
11
+ try {
12
+ const result = await originalMethod.apply(this, args);
13
+ const end = process.hrtime(start);
14
+ const durationInMilliseconds = end[0] * 1000 + end[1] / 1e6;
15
+ logger.info(` ${propertyKey} method took ${durationInMilliseconds.toFixed(2)} ms to execute`)
16
+ return result;
17
+ } catch (error) {
18
+ throw error;
19
+ }
20
+ };
21
+ return descriptor;
22
+
23
+ }
24
+
25
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,83 @@
1
+ import {Utilities} from "./utilities";
2
+ import winston from "winston";
3
+ import * as path from "path";
4
+ import * as fs from "fs";
5
+
6
+ export enum LogLevels {
7
+ INFO = "INFO", ERROR = "ERROR", DEBUG = "DEBUG", LOG = "LOG"
8
+ }
9
+
10
+ export class Logger {
11
+ private readonly winstonLogger: any;
12
+ public tag: string = "[UNTAGGED]";
13
+
14
+ private logFormat: winston.Logform.Format = winston.format.printf((tmp: winston.Logform.TransformableInfo): string => {
15
+ const {time, file, level, message} = tmp;
16
+ return `${JSON.stringify({time, file: file?.replaceAll("\\", "/"), level, message})},`;
17
+ });
18
+
19
+ constructor(tag: string) {
20
+ const fileName: string = this.getFileName();
21
+ const logsDirectory = "logs";
22
+ const logFilePath = path.join(logsDirectory, fileName + ".json");
23
+
24
+ if (!fs.existsSync(logsDirectory)) {
25
+ fs.mkdirSync(logsDirectory);
26
+ }
27
+ this.tag = tag;
28
+ this.winstonLogger = winston.createLogger({
29
+ format: winston.format.json(),
30
+ transports: [new winston.transports.File({filename: logFilePath, format: this.logFormat})],
31
+ });
32
+ }
33
+
34
+ private getFileName(): string {
35
+ const now = new Date();
36
+ return now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
37
+ }
38
+
39
+ public execStart(prefix: string = ""): any {
40
+ this.print(LogLevels.INFO, `${prefix} - Execution started`);
41
+ return performance.now();
42
+ }
43
+
44
+ public execStop(prefix: string = "", startTime: any, error: boolean = false): any {
45
+ switch (error) {
46
+ case true: {
47
+ this.print(LogLevels.ERROR, `${prefix} - Execution ended due to an error. Execution time: ${performance.now() - startTime} ms`);
48
+ break;
49
+ }
50
+ case false: {
51
+ this.print(LogLevels.INFO, `${prefix} - Execution ended successfully. Execution time: ${performance.now() - startTime} ms`);
52
+ break;
53
+ }
54
+ }
55
+ }
56
+
57
+ public info(...data: any): void {
58
+ this.print(LogLevels.INFO, ...data);
59
+ }
60
+
61
+ public debug(...data: any): void {
62
+ this.print(LogLevels.DEBUG, ...data);
63
+ }
64
+
65
+ public log(...data: any): void {
66
+ this.print(LogLevels.LOG, ...data);
67
+ }
68
+
69
+ public error(...data: any): void {
70
+ this.print(LogLevels.ERROR, ...data);
71
+ }
72
+
73
+ private print(level: LogLevels = LogLevels.INFO, ...data: any): void {
74
+ const now = new Date();
75
+ // Utilities.getNowDateString();
76
+ this.winstonLogger.defaultMeta = {
77
+ file: this.tag, time: now, level
78
+ };
79
+ this.winstonLogger[level.toLowerCase()](...data);
80
+ // @ts-ignore
81
+ console[level.toLowerCase()](`[${level}][${now}][${this.tag.split("\\").pop()}]`, ...data);
82
+ }
83
+ }
package/src/orm.ts ADDED
@@ -0,0 +1,120 @@
1
+ // @ts-ignore
2
+ import * as Firebird from "es-node-firebird";
3
+ import {Logger} from "./logger";
4
+ import {Database, Options, Transaction} from "node-firebird";
5
+
6
+
7
+ const quote = (value: string): string => {
8
+ return "\"" + value + "\"";
9
+ };
10
+ const testConnection = (options: Options): Promise<any> => {
11
+ const logger: Logger = new Logger(__filename);
12
+ return new Promise((resolve): void => {
13
+ Firebird.attach(options, (err: any, db: any): void => {
14
+ if (err) {
15
+ logger.error("La connessione con il DATABASE non è andata a buon fine.");
16
+ return resolve(false);
17
+ }
18
+ logger.info("DATABASE connesso.");
19
+ return resolve(true);
20
+ })
21
+ })
22
+ }
23
+
24
+ const query = (options: Options, query: string, parameters: any[] = []): Promise<any> => {
25
+ return new Promise((resolve, reject): void => {
26
+ Firebird.attach(options, (err: any, db: {
27
+ query: (arg0: any, arg1: any[], arg2: (err: any, result: any) => void) => void; detach: () => void;
28
+ }) => {
29
+ if (err) {
30
+ return reject(err);
31
+ }
32
+ db.query(query, parameters, (error: any, result: any) => {
33
+ if (error) {
34
+ db.detach();
35
+ return reject(error);
36
+ }
37
+ db.detach();
38
+ return resolve(result);
39
+ });
40
+ });
41
+ });
42
+ }
43
+ const execute = (options: Options, query: string, parameters: any = []): Promise<any> => {
44
+ return new Promise((resolve, reject): void => {
45
+ Firebird.attach(options, (err: any, db: {
46
+ execute: (arg0: any, arg1: any, arg2: (error: any, result: any) => void) => void; detach: () => void;
47
+ }) => {
48
+ if (err) {
49
+ return reject(err);
50
+ }
51
+
52
+ db.execute(query, parameters, (error, result): void => {
53
+ if (error) {
54
+ db.detach();
55
+ return reject(error);
56
+ }
57
+ db.detach();
58
+ return resolve(result);
59
+ });
60
+ });
61
+ });
62
+ }
63
+
64
+ const trimParam = (param: any): string => {
65
+ if (typeof param === "string" || param instanceof String) {
66
+ return param.trim();
67
+ }
68
+ return param;
69
+ }
70
+
71
+ const connect = (options: Options): Promise<any> => {
72
+ return new Promise((resolve, reject): void => {
73
+ Firebird.attach(options, function (err: any, db: any): void {
74
+ if (err) return reject(err); else return resolve(db);
75
+ });
76
+ });
77
+ }
78
+
79
+ const startTransaction = (db: Database): Promise<any> => {
80
+ return new Promise((resolve, reject): void => {
81
+ db.transaction(Firebird.ISOLATION_READ_COMMITTED, function (err: any, transaction: any) {
82
+ if (err) return reject(err); else return resolve(transaction);
83
+ });
84
+ });
85
+ }
86
+ const executeQueries = (transaction: Transaction, queries: string[], params: any[]) => {
87
+ return queries.reduce((promiseChain: any, currentQuery: any, index: any) => {
88
+ return promiseChain.then(() => new Promise((resolve, reject): void => {
89
+ transaction.query(currentQuery, params[index], (err: any, result: any): void => {
90
+ if (err) return reject(err); else return resolve(result);
91
+ });
92
+ }));
93
+ }, Promise.resolve());
94
+ }
95
+
96
+ const commitTransaction = (transaction: Transaction): Promise<any> => {
97
+ return new Promise((resolve, reject): void => {
98
+ transaction.commit((err: any): void => {
99
+ if (err) return reject(err); else return resolve('Transaction committed successfully.');
100
+ });
101
+ });
102
+ }
103
+
104
+ interface Orm {
105
+ quote: (value: string) => string,
106
+ testConnection: (options: Options) => Promise<any>,
107
+ query: (options: Options, query: any, parameters?: any[]) => Promise<any>,
108
+ execute: (options: Options, query: any, parameters?: any[]) => Promise<any>,
109
+ trimParam: (param: any) => string,
110
+ connect: (options: Options) => Promise<any>,
111
+ startTransaction: (db: Database) => Promise<any>,
112
+ executeQueries: (transaction: Transaction, queries: string[], params: any[]) => any,
113
+ commitTransaction: (transaction: Transaction) => Promise<any>
114
+ }
115
+
116
+ export const Orm: Orm = {
117
+ quote, testConnection, query, execute, trimParam, connect, startTransaction, executeQueries, commitTransaction
118
+ }
119
+
120
+
@@ -0,0 +1,180 @@
1
+ import {Response} from 'express';
2
+
3
+
4
+ enum STATUS_CODE {
5
+ OK = 0, WARNING = 1, ERROR = 2,
6
+ }
7
+
8
+ const parseDate = (date: string) => {
9
+ const parts: string[] = date.split("/");
10
+ return new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
11
+ }
12
+
13
+ const sendOKMessage = (res: Response, message: string): Response => {
14
+ return res.send({
15
+ severity: "success", status: 200, statusCode: STATUS_CODE.OK, message,
16
+ });
17
+ }
18
+
19
+
20
+ const getNowDateString = (): string => {
21
+ const now: Date = new Date();
22
+ const day: string | number = now.getDate() < 9 ? "0" + now.getDate() : now.getDate();
23
+ const month: string | number = (now.getMonth() + 1) < 9 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
24
+ const year: number = now.getFullYear();
25
+ const hours: string | number = now.getHours() < 9 ? "0" + now.getHours() : now.getHours();
26
+ const minutes: string | number = now.getMinutes() < 9 ? "0" + now.getMinutes() : now.getMinutes();
27
+ const seconds: string | number = now.getSeconds() < 9 ? "0" + now.getSeconds() : now.getSeconds();
28
+ return day + "." + month + "." + year + " " + hours + ":" + minutes + ":" + seconds;
29
+ }
30
+
31
+
32
+ const sendErrorMessage = (res: Response, error: any, tag: string = "[BASE ERROR]", status: number = 500): Response => {
33
+ return res.status(status).send({
34
+ severity: "error",
35
+ status: 500,
36
+ statusCode: STATUS_CODE.ERROR,
37
+ message: " Si è verificato un errore",
38
+ error: tag + ": " + error,
39
+ });
40
+ }
41
+
42
+ const sendBaseResponse = (res: Response, payload: any): Response => {
43
+ try {
44
+ payload = JSON.parse(JSON.stringify(payload));
45
+ const clearPayload = payload; // this.keysToCamel(payload);
46
+ const response = {
47
+ Status: {
48
+ errorCode: "0", errorDescription: "",
49
+ }, Result: clearPayload, Message: ""
50
+ };
51
+ return res.send(response);
52
+ } catch (error) {
53
+ return sendErrorMessage(res, "Errore nell'invio della risposta: " + error, "[UTILITIES]", 500);
54
+ }
55
+ }
56
+
57
+
58
+ const toCamel = (s: any) => {
59
+ return s.replace(/([-_][a-z])/gi, ($1: string) => {
60
+ return $1.toUpperCase().replace("-", "").replace("_", "");
61
+ });
62
+ };
63
+
64
+ const isArray = (a: any): boolean => {
65
+ return Array.isArray(a);
66
+ };
67
+
68
+ const isObject = (o: any): boolean => {
69
+ return o === Object(o) && !isArray(o) && typeof o !== "function";
70
+ };
71
+
72
+
73
+ const keysToCamel = (o: any): any => {
74
+ if (isObject(o)) {
75
+ const n = {};
76
+
77
+ Object.keys(o).forEach((k: any) => {
78
+ // @ts-ignore
79
+ n[toCamel(k)] = keysToCamel(o[k]);
80
+ });
81
+ return n;
82
+ } else if (isArray(o)) {
83
+ return o.map((i: any) => {
84
+ return keysToCamel(i);
85
+ });
86
+ }
87
+
88
+ return o;
89
+ };
90
+
91
+ const addStartingZeros = (num: number, totalLength: number): string => {
92
+ return String(num).padStart(totalLength, '0');
93
+ }
94
+
95
+ const dateToMoncler = (dData: Date, bAddMs: boolean = false): string => {
96
+ const yy: number = dData.getFullYear();
97
+ const mm: string = addStartingZeros(dData.getMonth() + 1, 2);
98
+ const dd: string = addStartingZeros(dData.getDate(), 2);
99
+ const hh: string = addStartingZeros(dData.getHours(), 2);
100
+ const nn: string = addStartingZeros(dData.getMinutes(), 2);
101
+ const ss: string = addStartingZeros(dData.getSeconds(), 2);
102
+ const ms: string = addStartingZeros(dData.getMilliseconds(), 3);
103
+ if (bAddMs) {
104
+ return yy + mm + dd + hh + nn + ss + ms;
105
+ } else {
106
+ return yy + mm + dd + hh + nn + ss;
107
+ }
108
+ }
109
+
110
+ const dateToSql = (dData: Date, bAddMs: boolean = false): string => {
111
+ const yy: number = dData.getFullYear();
112
+ const mm: string = addStartingZeros(dData.getMonth() + 1, 2);
113
+ const dd: string = addStartingZeros(dData.getDate(), 2);
114
+ const hh: string = addStartingZeros(dData.getHours(), 2);
115
+ const nn: string = addStartingZeros(dData.getMinutes(), 2);
116
+ const ss: string = addStartingZeros(dData.getSeconds(), 2);
117
+ const ms: string = addStartingZeros(dData.getMilliseconds(), 3);
118
+ if (bAddMs) {
119
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss + '.' + ms;
120
+ } else {
121
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss;
122
+
123
+ }
124
+ }
125
+
126
+ const dateToSimple = (dData: Date): string => {
127
+ const yy: number = dData.getFullYear();
128
+ const mm: string = addStartingZeros(dData.getMonth() + 1, 2);
129
+ const dd: string = addStartingZeros(dData.getDate(), 2);
130
+ return dd + '-' + mm + '-' + yy;
131
+ }
132
+
133
+ const sendExecMessage = (res: Response, executionObject: any, title: string): Response => {
134
+ try {
135
+ let sSql = "";
136
+ let response = {
137
+ Status: {
138
+ errorCode: "0", errorDescription: "",
139
+ }, Sql: sSql, ID: executionObject?.id, Title: title
140
+ };
141
+ return res.send(response);
142
+ } catch (error) {
143
+ return sendErrorMessage(res, "Errore nell'invio della risposta: " + error, title, 500);
144
+ }
145
+ }
146
+
147
+ interface Utilities {
148
+ parseDate: (date: string) => Date,
149
+ sendOKMessage: (res: Response, message: string) => Response,
150
+ sendExecMessage: (res: Response, executionObject: any, title: string) => Response,
151
+ getNowDateString: () => {},
152
+ sendErrorMessage: (res: Response, error: any, tag?: string, status?: number) => Response,
153
+ sendBaseResponse: (res: Response, payload: any) => Response,
154
+ toCamel: (s: any) => any,
155
+ isArray: (a: any) => boolean,
156
+ isObject: (o: any) => boolean,
157
+ keysToCamel: (o: any) => any,
158
+ addStartingZeros: (num: number, totalLength: number) => string,
159
+ dateToMoncler: (dData: Date, bAddMs?: boolean) => string,
160
+ dateToSql: (dData: Date, bAddMs?: boolean) => string,
161
+ dateToSimple: (dData: Date) => string
162
+ }
163
+
164
+ export const Utilities: Utilities = {
165
+ parseDate,
166
+ sendOKMessage,
167
+ sendExecMessage,
168
+ getNowDateString,
169
+ sendErrorMessage,
170
+ sendBaseResponse,
171
+ toCamel,
172
+ isArray,
173
+ isObject,
174
+ keysToCamel,
175
+ addStartingZeros,
176
+ dateToMoncler,
177
+ dateToSql,
178
+ dateToSimple
179
+ }
180
+
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es5",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": ".",
7
+ "esModuleInterop": true
8
+ },
9
+ "include": [
10
+ "src/index.ts",
11
+ "src/**/*.ts"
12
+ ],
13
+ "exclude": [
14
+ "node_modules"
15
+ ]
16
+ }
package/utilities.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { Response } from 'express';
2
+ interface Utilities {
3
+ parseDate: (date: string) => Date;
4
+ sendOKMessage: (res: Response, message: string) => Response;
5
+ sendExecMessage: (res: Response, executionObject: any, title: string) => Response;
6
+ getNowDateString: () => {};
7
+ sendErrorMessage: (res: Response, error: any, tag?: string, status?: number) => Response;
8
+ sendBaseResponse: (res: Response, payload: any) => Response;
9
+ toCamel: (s: any) => any;
10
+ isArray: (a: any) => boolean;
11
+ isObject: (o: any) => boolean;
12
+ keysToCamel: (o: any) => any;
13
+ addStartingZeros: (num: number, totalLength: number) => string;
14
+ dateToMoncler: (dData: Date, bAddMs?: boolean) => string;
15
+ dateToSql: (dData: Date, bAddMs?: boolean) => string;
16
+ dateToSimple: (dData: Date) => string;
17
+ }
18
+ export declare const Utilities: Utilities;
19
+ export {};
package/utilities.js ADDED
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Utilities = void 0;
4
+ var STATUS_CODE;
5
+ (function (STATUS_CODE) {
6
+ STATUS_CODE[STATUS_CODE["OK"] = 0] = "OK";
7
+ STATUS_CODE[STATUS_CODE["WARNING"] = 1] = "WARNING";
8
+ STATUS_CODE[STATUS_CODE["ERROR"] = 2] = "ERROR";
9
+ })(STATUS_CODE || (STATUS_CODE = {}));
10
+ var parseDate = function (date) {
11
+ var parts = date.split("/");
12
+ return new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
13
+ };
14
+ var sendOKMessage = function (res, message) {
15
+ return res.send({
16
+ severity: "success", status: 200, statusCode: STATUS_CODE.OK,
17
+ message: message,
18
+ });
19
+ };
20
+ var getNowDateString = function () {
21
+ var now = new Date();
22
+ var day = now.getDate() < 9 ? "0" + now.getDate() : now.getDate();
23
+ var month = (now.getMonth() + 1) < 9 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
24
+ var year = now.getFullYear();
25
+ var hours = now.getHours() < 9 ? "0" + now.getHours() : now.getHours();
26
+ var minutes = now.getMinutes() < 9 ? "0" + now.getMinutes() : now.getMinutes();
27
+ var seconds = now.getSeconds() < 9 ? "0" + now.getSeconds() : now.getSeconds();
28
+ return day + "." + month + "." + year + " " + hours + ":" + minutes + ":" + seconds;
29
+ };
30
+ var sendErrorMessage = function (res, error, tag, status) {
31
+ if (tag === void 0) { tag = "[BASE ERROR]"; }
32
+ if (status === void 0) { status = 500; }
33
+ return res.status(status).send({
34
+ severity: "error",
35
+ status: 500,
36
+ statusCode: STATUS_CODE.ERROR,
37
+ message: " Si è verificato un errore",
38
+ error: tag + ": " + error,
39
+ });
40
+ };
41
+ var sendBaseResponse = function (res, payload) {
42
+ try {
43
+ payload = JSON.parse(JSON.stringify(payload));
44
+ var clearPayload = payload; // this.keysToCamel(payload);
45
+ var response = {
46
+ Status: {
47
+ errorCode: "0", errorDescription: "",
48
+ }, Result: clearPayload, Message: ""
49
+ };
50
+ return res.send(response);
51
+ }
52
+ catch (error) {
53
+ return sendErrorMessage(res, "Errore nell'invio della risposta: " + error, "[UTILITIES]", 500);
54
+ }
55
+ };
56
+ var toCamel = function (s) {
57
+ return s.replace(/([-_][a-z])/gi, function ($1) {
58
+ return $1.toUpperCase().replace("-", "").replace("_", "");
59
+ });
60
+ };
61
+ var isArray = function (a) {
62
+ return Array.isArray(a);
63
+ };
64
+ var isObject = function (o) {
65
+ return o === Object(o) && !isArray(o) && typeof o !== "function";
66
+ };
67
+ var keysToCamel = function (o) {
68
+ if (isObject(o)) {
69
+ var n_1 = {};
70
+ Object.keys(o).forEach(function (k) {
71
+ // @ts-ignore
72
+ n_1[toCamel(k)] = keysToCamel(o[k]);
73
+ });
74
+ return n_1;
75
+ }
76
+ else if (isArray(o)) {
77
+ return o.map(function (i) {
78
+ return keysToCamel(i);
79
+ });
80
+ }
81
+ return o;
82
+ };
83
+ var addStartingZeros = function (num, totalLength) {
84
+ return String(num).padStart(totalLength, '0');
85
+ };
86
+ var dateToMoncler = function (dData, bAddMs) {
87
+ if (bAddMs === void 0) { bAddMs = false; }
88
+ var yy = dData.getFullYear();
89
+ var mm = addStartingZeros(dData.getMonth() + 1, 2);
90
+ var dd = addStartingZeros(dData.getDate(), 2);
91
+ var hh = addStartingZeros(dData.getHours(), 2);
92
+ var nn = addStartingZeros(dData.getMinutes(), 2);
93
+ var ss = addStartingZeros(dData.getSeconds(), 2);
94
+ var ms = addStartingZeros(dData.getMilliseconds(), 3);
95
+ if (bAddMs) {
96
+ return yy + mm + dd + hh + nn + ss + ms;
97
+ }
98
+ else {
99
+ return yy + mm + dd + hh + nn + ss;
100
+ }
101
+ };
102
+ var dateToSql = function (dData, bAddMs) {
103
+ if (bAddMs === void 0) { bAddMs = false; }
104
+ var yy = dData.getFullYear();
105
+ var mm = addStartingZeros(dData.getMonth() + 1, 2);
106
+ var dd = addStartingZeros(dData.getDate(), 2);
107
+ var hh = addStartingZeros(dData.getHours(), 2);
108
+ var nn = addStartingZeros(dData.getMinutes(), 2);
109
+ var ss = addStartingZeros(dData.getSeconds(), 2);
110
+ var ms = addStartingZeros(dData.getMilliseconds(), 3);
111
+ if (bAddMs) {
112
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss + '.' + ms;
113
+ }
114
+ else {
115
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss;
116
+ }
117
+ };
118
+ var dateToSimple = function (dData) {
119
+ var yy = dData.getFullYear();
120
+ var mm = addStartingZeros(dData.getMonth() + 1, 2);
121
+ var dd = addStartingZeros(dData.getDate(), 2);
122
+ return dd + '-' + mm + '-' + yy;
123
+ };
124
+ var sendExecMessage = function (res, executionObject, title) {
125
+ try {
126
+ var sSql = "";
127
+ var response = {
128
+ Status: {
129
+ errorCode: "0", errorDescription: "",
130
+ }, Sql: sSql, ID: executionObject === null || executionObject === void 0 ? void 0 : executionObject.id, Title: title
131
+ };
132
+ return res.send(response);
133
+ }
134
+ catch (error) {
135
+ return sendErrorMessage(res, "Errore nell'invio della risposta: " + error, title, 500);
136
+ }
137
+ };
138
+ exports.Utilities = {
139
+ parseDate: parseDate,
140
+ sendOKMessage: sendOKMessage,
141
+ sendExecMessage: sendExecMessage,
142
+ getNowDateString: getNowDateString,
143
+ sendErrorMessage: sendErrorMessage,
144
+ sendBaseResponse: sendBaseResponse,
145
+ toCamel: toCamel,
146
+ isArray: isArray,
147
+ isObject: isObject,
148
+ keysToCamel: keysToCamel,
149
+ addStartingZeros: addStartingZeros,
150
+ dateToMoncler: dateToMoncler,
151
+ dateToSql: dateToSql,
152
+ dateToSimple: dateToSimple
153
+ };