emilsoftware-utilities 1.0.0

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,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>
@@ -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;
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.boundClass = exports.boundMethod = void 0;
4
+ /**
5
+ * Return a descriptor removing the value and returning a getter
6
+ * The getter will return a .bind version of the function
7
+ * and memoize the result against a symbol on the instance
8
+ */
9
+ function boundMethod(target, key, descriptor) {
10
+ var fn = descriptor === null || descriptor === void 0 ? void 0 : descriptor.value;
11
+ if (typeof fn !== 'function') {
12
+ throw new TypeError("@boundMethod decorator can only be applied to methods not: ".concat(typeof fn));
13
+ }
14
+ // In IE11 calling Object.defineProperty has a side effect of evaluating the
15
+ // getter for the property which is being replaced. This causes infinite
16
+ // recursion and an "Out of stack space" error.
17
+ var definingProperty = false;
18
+ return {
19
+ configurable: true,
20
+ get: function () {
21
+ // eslint-disable-next-line no-prototype-builtins
22
+ if (definingProperty || this === target.prototype || this.hasOwnProperty(key) ||
23
+ typeof fn !== 'function') {
24
+ return fn;
25
+ }
26
+ var boundFn = fn.bind(this);
27
+ definingProperty = true;
28
+ if (key) {
29
+ Object.defineProperty(this, key, {
30
+ configurable: true,
31
+ get: function () {
32
+ return boundFn;
33
+ },
34
+ set: function (value) {
35
+ fn = value;
36
+ // @ts-ignore
37
+ delete this[key];
38
+ }
39
+ });
40
+ }
41
+ definingProperty = false;
42
+ return boundFn;
43
+ },
44
+ set: function (value) {
45
+ fn = value;
46
+ }
47
+ };
48
+ }
49
+ exports.boundMethod = boundMethod;
50
+ /**
51
+ * Use boundMethod to bind all methods on the target.prototype
52
+ */
53
+ function boundClass(target) {
54
+ // (Using reflect to get all keys including symbols)
55
+ var keys;
56
+ // Use Reflect if exists
57
+ if (typeof Reflect !== 'undefined' && typeof Reflect.ownKeys === 'function') {
58
+ keys = Reflect.ownKeys(target.prototype);
59
+ }
60
+ else {
61
+ keys = Object.getOwnPropertyNames(target.prototype);
62
+ // Use symbols if support is provided
63
+ if (typeof Object.getOwnPropertySymbols === 'function') {
64
+ // @ts-ignore
65
+ keys = keys.concat(Object.getOwnPropertySymbols(target.prototype));
66
+ }
67
+ }
68
+ keys.forEach(function (key) {
69
+ // Ignore special case target method
70
+ if (key === 'constructor') {
71
+ return;
72
+ }
73
+ var descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
74
+ // Only methods need binding
75
+ if (typeof (descriptor === null || descriptor === void 0 ? void 0 : descriptor.value) === 'function') {
76
+ Object.defineProperty(target.prototype, key, boundMethod(target, key, descriptor));
77
+ }
78
+ });
79
+ return target;
80
+ }
81
+ exports.boundClass = boundClass;
82
+ function autobind() {
83
+ var args = [];
84
+ for (var _i = 0; _i < arguments.length; _i++) {
85
+ args[_i] = arguments[_i];
86
+ }
87
+ if (args.length === 1) {
88
+ // @ts-ignore
89
+ return boundClass.apply(void 0, args);
90
+ }
91
+ // @ts-ignore
92
+ return boundMethod.apply(void 0, args);
93
+ }
94
+ exports.default = autobind;
@@ -0,0 +1 @@
1
+ export declare 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
+ exports.logExecutionTime = void 0;
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.logExecutionTime = logExecutionTime;
@@ -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/dist/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/dist/orm.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export declare class Orm {
2
+ static RESULT_EXEC_OK: string;
3
+ static quote(value: string): string;
4
+ static testConnection(options: any): Promise<any>;
5
+ static query(options: any, query: any, parameters?: any[]): Promise<any>;
6
+ static execute(options: any, query: any, parameters?: any): Promise<unknown>;
7
+ static trimParam(param: any): any;
8
+ }
package/dist/orm.js ADDED
@@ -0,0 +1,106 @@
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 Orm = /** @class */ (function () {
31
+ function Orm() {
32
+ }
33
+ Orm.quote = function (value) {
34
+ return "\"" + value + "\"";
35
+ };
36
+ ;
37
+ Orm.testConnection = function (options) {
38
+ var logger = new logger_1.Logger(__filename);
39
+ return new Promise(function (resolve, reject) {
40
+ Firebird.attach(options, function (err, db) {
41
+ if (err) {
42
+ logger.error("La connessione con il DATABASE non è andata a buon fine.");
43
+ return resolve(false);
44
+ }
45
+ logger.info("DATABASE connesso.");
46
+ return resolve(true);
47
+ });
48
+ });
49
+ };
50
+ Orm.query = function (options, query, parameters) {
51
+ if (parameters === void 0) { parameters = []; }
52
+ return new Promise(function (resolve, reject) {
53
+ Firebird.attach(options, function (err, db) {
54
+ if (err) {
55
+ return reject(err);
56
+ }
57
+ db.query(query, parameters, function (error, result) {
58
+ if (error) {
59
+ db.detach();
60
+ return reject(error);
61
+ }
62
+ db.detach();
63
+ return resolve(result);
64
+ });
65
+ });
66
+ });
67
+ };
68
+ Orm.execute = function (options, query, parameters) {
69
+ var _this = this;
70
+ if (parameters === void 0) { parameters = []; }
71
+ return new Promise(function (resolve, reject) {
72
+ Firebird.attach(options, function (err, db) {
73
+ if (err) {
74
+ // tslint:disable-next-line:no-console
75
+ console.error(err);
76
+ return reject(err);
77
+ }
78
+ db.execute(query, parameters, function (error, result) {
79
+ if (error) {
80
+ db.detach();
81
+ // tslint:disable-next-line:no-console
82
+ console.log(query);
83
+ parameters.forEach(function (param, i) {
84
+ // tslint:disable-next-line:no-console
85
+ console.log(i + 1, param);
86
+ });
87
+ // tslint:disable-next-line:no-console
88
+ console.error(error);
89
+ return reject(error);
90
+ }
91
+ db.detach();
92
+ return resolve(_this.RESULT_EXEC_OK);
93
+ });
94
+ });
95
+ });
96
+ };
97
+ Orm.trimParam = function (param) {
98
+ if (typeof param === "string" || param instanceof String) {
99
+ return param.trim();
100
+ }
101
+ return param;
102
+ };
103
+ Orm.RESULT_EXEC_OK = "ok!";
104
+ return Orm;
105
+ }());
106
+ exports.Orm = Orm;
@@ -0,0 +1,21 @@
1
+ export declare class Utilities {
2
+ static parseDate(date: string): Date;
3
+ static STATUS_CODE: {
4
+ OK: number;
5
+ WARNING: number;
6
+ ERROR: number;
7
+ };
8
+ static sendOKMessage(res: any, message: any): any;
9
+ static getNowDateString(): string;
10
+ static sendErrorMessage(res: any, err: any, tag?: string, status?: number): any;
11
+ static sendOpenResponse(res: any, payload: any): any;
12
+ static sendOpenErrorMessage(res: any, err: any, tag?: string, status?: number): any;
13
+ private static toCamel;
14
+ private static isArray;
15
+ private static isObject;
16
+ static keysToCamel(o: any): any;
17
+ static addStartingZeros(num: number, totalLength: number): string;
18
+ static dateToMoncler(dData: Date, bAddMs?: boolean): string;
19
+ static dateToSql(dData: Date, bAddMs?: boolean): string;
20
+ static dateToSimple(dData: Date): string;
21
+ }
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Utilities = void 0;
4
+ var Utilities = /** @class */ (function () {
5
+ function Utilities() {
6
+ }
7
+ Utilities.parseDate = function (date) {
8
+ var parts = date.split("/");
9
+ return new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
10
+ };
11
+ Utilities.sendOKMessage = function (res, message) {
12
+ return res.send({
13
+ severity: "success", status: 200, statusCode: this.STATUS_CODE.OK,
14
+ message: message,
15
+ });
16
+ };
17
+ Utilities.getNowDateString = function () {
18
+ var now = new Date();
19
+ var day = now.getDate() < 9 ? "0" + now.getDate() : now.getDate();
20
+ var month = (now.getMonth() + 1) < 9 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
21
+ var year = now.getFullYear();
22
+ var hours = now.getHours() < 9 ? "0" + now.getHours() : now.getHours();
23
+ var minutes = now.getMinutes() < 9 ? "0" + now.getMinutes() : now.getMinutes();
24
+ var seconds = now.getSeconds() < 9 ? "0" + now.getSeconds() : now.getSeconds();
25
+ return day + "." + month + "." + year + " " + hours + ":" + minutes + ":" + seconds;
26
+ };
27
+ Utilities.sendErrorMessage = function (res, err, tag, status) {
28
+ if (tag === void 0) { tag = "[BASE ERROR]"; }
29
+ if (status === void 0) { status = 500; }
30
+ // tslint:disable-next-line:no-console
31
+ console.error(err);
32
+ return res.status(status).send({
33
+ severity: "error",
34
+ status: 500,
35
+ statusCode: this.STATUS_CODE.ERROR,
36
+ message: " Si è verificato un errore",
37
+ error: tag + ": " + err,
38
+ });
39
+ };
40
+ // Risposte per funzioni in stile ES
41
+ Utilities.sendOpenResponse = 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 this.sendOpenErrorMessage(res, "Errore nell'invio della risposta: " + error, "[UTILITIES]", 500);
54
+ }
55
+ };
56
+ Utilities.sendOpenErrorMessage = function (res, err, tag, status) {
57
+ if (tag === void 0) { tag = "[BASE ERROR]"; }
58
+ if (status === void 0) { status = 500; }
59
+ return res.status(status).send({
60
+ Status: {
61
+ errorCode: "500", errorDescription: err,
62
+ }, Result: [], Message: err,
63
+ });
64
+ };
65
+ Utilities.toCamel = function (s) {
66
+ return s.replace(/([-_][a-z])/gi, function ($1) {
67
+ return $1.toUpperCase().replace("-", "").replace("_", "");
68
+ });
69
+ };
70
+ ;
71
+ Utilities.isArray = function (a) {
72
+ return Array.isArray(a);
73
+ };
74
+ ;
75
+ Utilities.isObject = function (o) {
76
+ return o === Object(o) && !this.isArray(o) && typeof o !== "function";
77
+ };
78
+ ;
79
+ Utilities.keysToCamel = function (o) {
80
+ var _this = this;
81
+ if (this.isObject(o)) {
82
+ var n_1 = {};
83
+ Object.keys(o).forEach(function (k) {
84
+ // @ts-ignore
85
+ n_1[_this.toCamel(k)] = _this.keysToCamel(o[k]);
86
+ });
87
+ return n_1;
88
+ }
89
+ else if (this.isArray(o)) {
90
+ return o.map(function (i) {
91
+ return _this.keysToCamel(i);
92
+ });
93
+ }
94
+ return o;
95
+ };
96
+ ;
97
+ Utilities.addStartingZeros = function (num, totalLength) {
98
+ return String(num).padStart(totalLength, '0');
99
+ };
100
+ Utilities.dateToMoncler = function (dData, bAddMs) {
101
+ if (bAddMs === void 0) { bAddMs = false; }
102
+ var yy = dData.getFullYear();
103
+ var mm = this.addStartingZeros(dData.getMonth() + 1, 2);
104
+ var dd = this.addStartingZeros(dData.getDate(), 2);
105
+ var hh = this.addStartingZeros(dData.getHours(), 2);
106
+ var nn = this.addStartingZeros(dData.getMinutes(), 2);
107
+ var ss = this.addStartingZeros(dData.getSeconds(), 2);
108
+ var ms = this.addStartingZeros(dData.getMilliseconds(), 3);
109
+ if (bAddMs) {
110
+ return yy + mm + dd + hh + nn + ss + ms;
111
+ }
112
+ else {
113
+ return yy + mm + dd + hh + nn + ss;
114
+ }
115
+ };
116
+ Utilities.dateToSql = function (dData, bAddMs) {
117
+ if (bAddMs === void 0) { bAddMs = false; }
118
+ var yy = dData.getFullYear();
119
+ var mm = this.addStartingZeros(dData.getMonth() + 1, 2);
120
+ var dd = this.addStartingZeros(dData.getDate(), 2);
121
+ var hh = this.addStartingZeros(dData.getHours(), 2);
122
+ var nn = this.addStartingZeros(dData.getMinutes(), 2);
123
+ var ss = this.addStartingZeros(dData.getSeconds(), 2);
124
+ var ms = this.addStartingZeros(dData.getMilliseconds(), 3);
125
+ if (bAddMs) {
126
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss + '.' + ms;
127
+ }
128
+ else {
129
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss;
130
+ }
131
+ };
132
+ Utilities.dateToSimple = function (dData) {
133
+ var yy = dData.getFullYear();
134
+ var mm = this.addStartingZeros(dData.getMonth() + 1, 2);
135
+ var dd = this.addStartingZeros(dData.getDate(), 2);
136
+ return dd + '-' + mm + '-' + yy;
137
+ };
138
+ Utilities.STATUS_CODE = {
139
+ OK: 0, WARNING: 1, ERROR: 2,
140
+ };
141
+ return Utilities;
142
+ }());
143
+ exports.Utilities = Utilities;
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "emilsoftware-utilities",
3
+ "version": "1.0.0",
4
+ "description": "Utilities for EmilSoftware",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1",
8
+ "build": "tsc",
9
+ "prepublishOnly": "npm run build"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/mttdev382/emilsoftware-utilities.git"
14
+ },
15
+ "author": "",
16
+ "license": "ISC",
17
+ "bugs": {
18
+ "url": "https://github.com/mttdev382/emilsoftware-utilities/issues"
19
+ },
20
+ "homepage": "https://github.com/mttdev382/emilsoftware-utilities#readme",
21
+ "dependencies": {
22
+ "es-node-firebird": "^1.1.8",
23
+ "winston": "^3.11.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^20.10.5",
27
+ "typescript": "^5.3.3"
28
+ }
29
+ }
@@ -0,0 +1,92 @@
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 function boundMethod(target:any, key: any, descriptor: any) {
7
+ let fn = descriptor?.value;
8
+
9
+ if (typeof fn !== 'function') {
10
+ throw new TypeError(`@boundMethod decorator can only be applied to methods not: ${typeof fn}`);
11
+ }
12
+
13
+ // In IE11 calling Object.defineProperty has a side effect of evaluating the
14
+ // getter for the property which is being replaced. This causes infinite
15
+ // recursion and an "Out of stack space" error.
16
+ let definingProperty = false;
17
+
18
+ return {
19
+ configurable: true,
20
+ get() {
21
+ // eslint-disable-next-line no-prototype-builtins
22
+ if (definingProperty || this === target.prototype || this.hasOwnProperty(key as string | number | symbol) ||
23
+ typeof fn !== 'function') {
24
+ return fn;
25
+ }
26
+
27
+ const boundFn = fn.bind(this);
28
+ definingProperty = true;
29
+ if (key) {
30
+ Object.defineProperty(this, key, {
31
+ configurable: true,
32
+ get() {
33
+ return boundFn;
34
+ },
35
+ set(value) {
36
+ fn = value;
37
+ // @ts-ignore
38
+ delete this[key];
39
+ }
40
+ });
41
+ }
42
+ definingProperty = false;
43
+ return boundFn;
44
+ },
45
+ set(value: any) {
46
+ fn = value;
47
+ }
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Use boundMethod to bind all methods on the target.prototype
53
+ */
54
+ export function boundClass(target: any) {
55
+ // (Using reflect to get all keys including symbols)
56
+ let keys;
57
+ // Use Reflect if exists
58
+ if (typeof Reflect !== 'undefined' && typeof Reflect.ownKeys === 'function') {
59
+ keys = Reflect.ownKeys(target.prototype);
60
+ } else {
61
+ keys = Object.getOwnPropertyNames(target.prototype);
62
+ // Use symbols if support is provided
63
+ if (typeof Object.getOwnPropertySymbols === 'function') {
64
+ // @ts-ignore
65
+ keys = keys.concat(Object.getOwnPropertySymbols(target.prototype));
66
+ }
67
+ }
68
+
69
+ keys.forEach(key => {
70
+ // Ignore special case target method
71
+ if (key === 'constructor') {
72
+ return;
73
+ }
74
+
75
+ const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
76
+
77
+ // Only methods need binding
78
+ if (typeof descriptor?.value === 'function') {
79
+ Object.defineProperty(target.prototype, key, boundMethod(target, key, descriptor));
80
+ }
81
+ });
82
+ return target;
83
+ }
84
+
85
+ export default function autobind(...args: any[]) {
86
+ if (args.length === 1) {
87
+ // @ts-ignore
88
+ return boundClass(...args);
89
+ }
90
+ // @ts-ignore
91
+ return boundMethod(...args);
92
+ }
@@ -0,0 +1,24 @@
1
+ import {Logger} from "../logger";
2
+
3
+ export function logExecutionTime(fileName: string = "") {
4
+ return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
5
+ const logger: Logger = new Logger(fileName);
6
+ const originalMethod = descriptor.value;
7
+ descriptor.value = async function (...args: any[]) {
8
+ const start = process.hrtime();
9
+ logger.info(` ${propertyKey} method execution started . . .`);
10
+ try {
11
+ const result = await originalMethod.apply(this, args);
12
+ const end = process.hrtime(start);
13
+ const durationInMilliseconds = end[0] * 1000 + end[1] / 1e6;
14
+ logger.info(` ${propertyKey} method took ${durationInMilliseconds.toFixed(2)} ms to execute`)
15
+ return result;
16
+ } catch (error) {
17
+ throw error;
18
+ }
19
+ };
20
+ return descriptor;
21
+
22
+ }
23
+
24
+ }
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,87 @@
1
+ // @ts-ignore
2
+ import * as Firebird from "es-node-firebird";
3
+ import {Logger} from "./logger";
4
+
5
+ export class Orm {
6
+ public static RESULT_EXEC_OK = "ok!";
7
+
8
+ public static quote(value: string) {
9
+ return "\"" + value + "\"";
10
+ };
11
+
12
+ public static testConnection(options: any): Promise<any> {
13
+ const logger: Logger = new Logger(__filename);
14
+ return new Promise((resolve, reject): void => {
15
+ Firebird.attach(options, (err: any, db: any): void => {
16
+ if (err) {
17
+ logger.error("La connessione con il DATABASE non è andata a buon fine.");
18
+ return resolve(false);
19
+ }
20
+ logger.info("DATABASE connesso.");
21
+ return resolve(true);
22
+ })
23
+ })
24
+ }
25
+
26
+
27
+ public static query(options: any, query: any, parameters: any[] = []): Promise<any> {
28
+ return new Promise((resolve, reject): void => {
29
+ Firebird.attach(options, (err: any, db: {
30
+ query: (arg0: any, arg1: any[], arg2: (err: any, result: any) => void) => void; detach: () => void;
31
+ }) => {
32
+ if (err) {
33
+ return reject(err);
34
+ }
35
+ db.query(query, parameters, (error: any, result: any) => {
36
+ if (error) {
37
+ db.detach();
38
+ return reject(error);
39
+ }
40
+ db.detach();
41
+ return resolve(result);
42
+ });
43
+ });
44
+ });
45
+ }
46
+
47
+
48
+ public static execute(options: any, query: any, parameters: any = []) {
49
+ return new Promise((resolve, reject) => {
50
+ Firebird.attach(options, (err: any, db: {
51
+ execute: (arg0: any, arg1: any, arg2: (error: any, result: any) => void) => void; detach: () => void;
52
+ }) => {
53
+ if (err) {
54
+ // tslint:disable-next-line:no-console
55
+ console.error(err);
56
+ return reject(err);
57
+ }
58
+
59
+ db.execute(query, parameters, (error, result) => {
60
+ if (error) {
61
+ db.detach();
62
+ // tslint:disable-next-line:no-console
63
+ console.log(query);
64
+ parameters.forEach((param: any, i: any) => {
65
+ // tslint:disable-next-line:no-console
66
+ console.log(i + 1, param);
67
+ })
68
+ // tslint:disable-next-line:no-console
69
+ console.error(error);
70
+ return reject(error);
71
+ }
72
+ db.detach();
73
+ return resolve(this.RESULT_EXEC_OK);
74
+ });
75
+ });
76
+ });
77
+ }
78
+
79
+ public static trimParam(param: any) {
80
+ if (typeof param === "string" || param instanceof String) {
81
+ return param.trim();
82
+ }
83
+ return param;
84
+ }
85
+ }
86
+
87
+
@@ -0,0 +1,144 @@
1
+ export class Utilities {
2
+
3
+ public static parseDate(date: string) {
4
+ const parts: string[] = date.split("/");
5
+ return new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
6
+ }
7
+
8
+ public static STATUS_CODE = {
9
+ OK: 0, WARNING: 1, ERROR: 2,
10
+ };
11
+
12
+ public static sendOKMessage(res: any, message: any) {
13
+ return res.send({
14
+ severity: "success", status: 200, statusCode: this.STATUS_CODE.OK, message,
15
+ });
16
+ }
17
+
18
+ public static getNowDateString() {
19
+ const now: Date = new Date();
20
+ const day: string | number = now.getDate() < 9 ? "0" + now.getDate() : now.getDate();
21
+ const month: string | number = (now.getMonth() + 1) < 9 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
22
+ const year: number = now.getFullYear();
23
+ const hours: string | number = now.getHours() < 9 ? "0" + now.getHours() : now.getHours();
24
+ const minutes: string | number = now.getMinutes() < 9 ? "0" + now.getMinutes() : now.getMinutes();
25
+ const seconds: string | number = now.getSeconds() < 9 ? "0" + now.getSeconds() : now.getSeconds();
26
+ return day + "." + month + "." + year + " " + hours + ":" + minutes + ":" + seconds;
27
+ }
28
+
29
+
30
+ public static sendErrorMessage(res: any, err: any, tag: string = "[BASE ERROR]", status: number = 500) {
31
+ // tslint:disable-next-line:no-console
32
+ console.error(err);
33
+ return res.status(status).send({
34
+ severity: "error",
35
+ status: 500,
36
+ statusCode: this.STATUS_CODE.ERROR,
37
+ message: " Si è verificato un errore",
38
+ error: tag + ": " + err,
39
+ });
40
+ }
41
+
42
+ // Risposte per funzioni in stile ES
43
+ public static sendOpenResponse(res: any, payload: any) {
44
+ try {
45
+ payload = JSON.parse(JSON.stringify(payload));
46
+ const clearPayload = payload; // this.keysToCamel(payload);
47
+ const response = {
48
+ Status: {
49
+ errorCode: "0", errorDescription: "",
50
+ }, Result: clearPayload, Message: ""
51
+ };
52
+ return res.send(response);
53
+ } catch (error) {
54
+ return this.sendOpenErrorMessage(res, "Errore nell'invio della risposta: " + error, "[UTILITIES]", 500);
55
+ }
56
+ }
57
+
58
+
59
+ public static sendOpenErrorMessage(res: any, err: any, tag = "[BASE ERROR]", status = 500) {
60
+ return res.status(status).send({
61
+ Status: {
62
+ errorCode: "500", errorDescription: err,
63
+ }, Result: [], Message: err,
64
+ });
65
+ }
66
+
67
+ private static toCamel(s: any) {
68
+ return s.replace(/([-_][a-z])/gi, ($1: string) => {
69
+ return $1.toUpperCase().replace("-", "").replace("_", "");
70
+ });
71
+ };
72
+
73
+ private static isArray(a: any) {
74
+ return Array.isArray(a);
75
+ };
76
+
77
+ private static isObject(o: any) {
78
+ return o === Object(o) && !this.isArray(o) && typeof o !== "function";
79
+ };
80
+
81
+ public static keysToCamel(o: any) {
82
+ if (this.isObject(o)) {
83
+ const n = {};
84
+
85
+ Object.keys(o).forEach((k: any) => {
86
+ // @ts-ignore
87
+ n[this.toCamel(k)] = this.keysToCamel(o[k]);
88
+ });
89
+
90
+ return n;
91
+ } else if (this.isArray(o)) {
92
+ return o.map((i: any) => {
93
+ return this.keysToCamel(i);
94
+ });
95
+ }
96
+
97
+ return o;
98
+ };
99
+
100
+ public static addStartingZeros(num: number, totalLength: number) {
101
+ return String(num).padStart(totalLength, '0');
102
+ }
103
+
104
+ public static dateToMoncler(dData: Date, bAddMs: boolean = false) {
105
+ const yy: number = dData.getFullYear();
106
+ const mm: string = this.addStartingZeros(dData.getMonth() + 1, 2);
107
+ const dd: string = this.addStartingZeros(dData.getDate(), 2);
108
+ const hh: string = this.addStartingZeros(dData.getHours(), 2);
109
+ const nn: string = this.addStartingZeros(dData.getMinutes(), 2);
110
+ const ss: string = this.addStartingZeros(dData.getSeconds(), 2);
111
+ const ms: string = this.addStartingZeros(dData.getMilliseconds(), 3);
112
+ if (bAddMs) {
113
+ return yy + mm + dd + hh + nn + ss + ms;
114
+ } else {
115
+ return yy + mm + dd + hh + nn + ss;
116
+ }
117
+ }
118
+
119
+ public static dateToSql(dData: Date, bAddMs: boolean = false) {
120
+ const yy: number = dData.getFullYear();
121
+ const mm: string = this.addStartingZeros(dData.getMonth() + 1, 2);
122
+ const dd: string = this.addStartingZeros(dData.getDate(), 2);
123
+ const hh: string = this.addStartingZeros(dData.getHours(), 2);
124
+ const nn: string = this.addStartingZeros(dData.getMinutes(), 2);
125
+ const ss: string = this.addStartingZeros(dData.getSeconds(), 2);
126
+ const ms: string = this.addStartingZeros(dData.getMilliseconds(), 3);
127
+ if (bAddMs) {
128
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss + '.' + ms;
129
+ } else {
130
+ return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss;
131
+
132
+ }
133
+ }
134
+
135
+ public static dateToSimple(dData: Date) {
136
+ const yy: number = dData.getFullYear();
137
+ const mm: string = this.addStartingZeros(dData.getMonth() + 1, 2);
138
+ const dd: string = this.addStartingZeros(dData.getDate(), 2);
139
+ return dd + '-' + mm + '-' + yy;
140
+ }
141
+
142
+
143
+ }
144
+
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es5",
4
+ "module": "commonjs",
5
+ "declaration": true,
6
+ "outDir": "./dist",
7
+ "esModuleInterop": true
8
+ },
9
+ "include": [
10
+ "src/**/*.ts"
11
+ ],
12
+ "exclude": [
13
+ "node_modules"
14
+ ]
15
+ }