emilsoftware-utilities 1.0.7 → 1.0.9

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,4 +1,5 @@
1
1
  "use strict";
2
+ // DECORATOR
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.boundClass = exports.boundMethod = void 0;
4
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import autobind from "./decorators/autobind";
2
- import logExecutionTime from "./decorators/log-execution-time";
1
+ import autobind from "./autobind";
2
+ import logExecutionTime from "./log-execution-time";
3
3
  import { Logger, LogLevels } from "./logger";
4
4
  import { Orm } from "./orm";
5
5
  import { Utilities } from "./utilities";
package/dist/index.js CHANGED
@@ -4,9 +4,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Utilities = exports.Orm = exports.LogLevels = exports.Logger = exports.logExecutionTime = exports.autobind = void 0;
7
- var autobind_1 = __importDefault(require("./decorators/autobind"));
7
+ var autobind_1 = __importDefault(require("./autobind"));
8
8
  exports.autobind = autobind_1.default;
9
- var log_execution_time_1 = __importDefault(require("./decorators/log-execution-time"));
9
+ var log_execution_time_1 = __importDefault(require("./log-execution-time"));
10
10
  exports.logExecutionTime = log_execution_time_1.default;
11
11
  var logger_1 = require("./logger");
12
12
  Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return logger_1.Logger; } });
@@ -36,7 +36,8 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
36
36
  }
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- var logger_1 = require("../logger");
39
+ // DECORATOR
40
+ var logger_1 = require("./logger");
40
41
  function logExecutionTime(fileName) {
41
42
  if (fileName === void 0) { fileName = ""; }
42
43
  return function (target, propertyKey, descriptor) {
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "emilsoftware-utilities",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "Utilities for EmilSoftware",
5
5
  "main": "index.js",
6
+ "files": [
7
+ "dist"
8
+ ],
6
9
  "scripts": {
7
10
  "test": "echo \"Error: no test specified\" && exit 1",
8
11
  "build": "tsc",
package/.idea/.name DELETED
@@ -1 +0,0 @@
1
- emilsoftware-utilities
@@ -1,12 +0,0 @@
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>
@@ -1,10 +0,0 @@
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>
package/.idea/modules.xml DELETED
@@ -1,8 +0,0 @@
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 DELETED
@@ -1,6 +0,0 @@
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>
@@ -1,15 +0,0 @@
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;
@@ -1,94 +0,0 @@
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;
@@ -1 +0,0 @@
1
- export default function logExecutionTime(fileName?: string): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
@@ -1,78 +0,0 @@
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
- var logger_1 = require("../logger");
40
- function logExecutionTime(fileName) {
41
- if (fileName === void 0) { fileName = ""; }
42
- return function (target, propertyKey, descriptor) {
43
- var logger = new logger_1.Logger(fileName);
44
- var originalMethod = descriptor.value;
45
- descriptor.value = function () {
46
- var args = [];
47
- for (var _i = 0; _i < arguments.length; _i++) {
48
- args[_i] = arguments[_i];
49
- }
50
- return __awaiter(this, void 0, void 0, function () {
51
- var start, result, end, durationInMilliseconds, error_1;
52
- return __generator(this, function (_a) {
53
- switch (_a.label) {
54
- case 0:
55
- start = process.hrtime();
56
- logger.info(" ".concat(propertyKey, " method execution started . . ."));
57
- _a.label = 1;
58
- case 1:
59
- _a.trys.push([1, 3, , 4]);
60
- return [4 /*yield*/, originalMethod.apply(this, args)];
61
- case 2:
62
- result = _a.sent();
63
- end = process.hrtime(start);
64
- durationInMilliseconds = end[0] * 1000 + end[1] / 1e6;
65
- logger.info(" ".concat(propertyKey, " method took ").concat(durationInMilliseconds.toFixed(2), " ms to execute"));
66
- return [2 /*return*/, result];
67
- case 3:
68
- error_1 = _a.sent();
69
- throw error_1;
70
- case 4: return [2 /*return*/];
71
- }
72
- });
73
- });
74
- };
75
- return descriptor;
76
- };
77
- }
78
- exports.default = logExecutionTime;
package/index.ts DELETED
@@ -1 +0,0 @@
1
- export {autobind, logExecutionTime, Logger, Orm, Utilities} from './dist';
@@ -1,92 +0,0 @@
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
- }
@@ -1,24 +0,0 @@
1
- import {Logger} from "../logger";
2
-
3
- export default 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/index.ts DELETED
@@ -1,6 +0,0 @@
1
- import autobind from "./decorators/autobind"
2
- import logExecutionTime from "./decorators/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};
package/src/logger.ts DELETED
@@ -1,83 +0,0 @@
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 DELETED
@@ -1,120 +0,0 @@
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
-
package/src/utilities.ts DELETED
@@ -1,161 +0,0 @@
1
- enum STATUS_CODE {
2
- OK = 0, WARNING = 1, ERROR = 2,
3
- }
4
-
5
- const parseDate = (date: string) => {
6
- const parts: string[] = date.split("/");
7
- return new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
8
- }
9
-
10
- const sendOKMessage = (res: any, message: any) => {
11
- return res.send({
12
- severity: "success", status: 200, statusCode: STATUS_CODE.OK, message,
13
- });
14
- }
15
-
16
-
17
- const getNowDateString = (): string => {
18
- const now: Date = new Date();
19
- const day: string | number = now.getDate() < 9 ? "0" + now.getDate() : now.getDate();
20
- const month: string | number = (now.getMonth() + 1) < 9 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
21
- const year: number = now.getFullYear();
22
- const hours: string | number = now.getHours() < 9 ? "0" + now.getHours() : now.getHours();
23
- const minutes: string | number = now.getMinutes() < 9 ? "0" + now.getMinutes() : now.getMinutes();
24
- const seconds: string | number = now.getSeconds() < 9 ? "0" + now.getSeconds() : now.getSeconds();
25
- return day + "." + month + "." + year + " " + hours + ":" + minutes + ":" + seconds;
26
- }
27
-
28
-
29
- const sendErrorMessage = (res: any, err: any, tag: string = "[BASE ERROR]", status: number = 500) => {
30
- return res.status(status).send({
31
- severity: "error",
32
- status: 500,
33
- statusCode: STATUS_CODE.ERROR,
34
- message: " Si è verificato un errore",
35
- error: tag + ": " + err,
36
- });
37
- }
38
-
39
- const sendBaseResponse = (res: any, payload: any) => {
40
- try {
41
- payload = JSON.parse(JSON.stringify(payload));
42
- const clearPayload = payload; // this.keysToCamel(payload);
43
- const response = {
44
- Status: {
45
- errorCode: "0", errorDescription: "",
46
- }, Result: clearPayload, Message: ""
47
- };
48
- return res.send(response);
49
- } catch (error) {
50
- return sendErrorMessage(res, "Errore nell'invio della risposta: " + error, "[UTILITIES]", 500);
51
- }
52
- }
53
-
54
-
55
- const toCamel = (s: any) => {
56
- return s.replace(/([-_][a-z])/gi, ($1: string) => {
57
- return $1.toUpperCase().replace("-", "").replace("_", "");
58
- });
59
- };
60
-
61
- const isArray = (a: any): boolean => {
62
- return Array.isArray(a);
63
- };
64
-
65
- const isObject = (o: any): boolean => {
66
- return o === Object(o) && !isArray(o) && typeof o !== "function";
67
- };
68
-
69
-
70
- const keysToCamel = (o: any) => {
71
- if (isObject(o)) {
72
- const n = {};
73
-
74
- Object.keys(o).forEach((k: any) => {
75
- // @ts-ignore
76
- n[toCamel(k)] = keysToCamel(o[k]);
77
- });
78
- return n;
79
- } else if (isArray(o)) {
80
- return o.map((i: any) => {
81
- return keysToCamel(i);
82
- });
83
- }
84
-
85
- return o;
86
- };
87
-
88
- const addStartingZeros = (num: number, totalLength: number): string => {
89
- return String(num).padStart(totalLength, '0');
90
- }
91
-
92
- const dateToMoncler = (dData: Date, bAddMs: boolean = false): string => {
93
- const yy: number = dData.getFullYear();
94
- const mm: string = addStartingZeros(dData.getMonth() + 1, 2);
95
- const dd: string = addStartingZeros(dData.getDate(), 2);
96
- const hh: string = addStartingZeros(dData.getHours(), 2);
97
- const nn: string = addStartingZeros(dData.getMinutes(), 2);
98
- const ss: string = addStartingZeros(dData.getSeconds(), 2);
99
- const ms: string = addStartingZeros(dData.getMilliseconds(), 3);
100
- if (bAddMs) {
101
- return yy + mm + dd + hh + nn + ss + ms;
102
- } else {
103
- return yy + mm + dd + hh + nn + ss;
104
- }
105
- }
106
-
107
- const dateToSql = (dData: Date, bAddMs: boolean = false): string => {
108
- const yy: number = dData.getFullYear();
109
- const mm: string = addStartingZeros(dData.getMonth() + 1, 2);
110
- const dd: string = addStartingZeros(dData.getDate(), 2);
111
- const hh: string = addStartingZeros(dData.getHours(), 2);
112
- const nn: string = addStartingZeros(dData.getMinutes(), 2);
113
- const ss: string = addStartingZeros(dData.getSeconds(), 2);
114
- const ms: string = addStartingZeros(dData.getMilliseconds(), 3);
115
- if (bAddMs) {
116
- return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss + '.' + ms;
117
- } else {
118
- return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + nn + ':' + ss;
119
-
120
- }
121
- }
122
-
123
- const dateToSimple = (dData: Date): string => {
124
- const yy: number = dData.getFullYear();
125
- const mm: string = addStartingZeros(dData.getMonth() + 1, 2);
126
- const dd: string = addStartingZeros(dData.getDate(), 2);
127
- return dd + '-' + mm + '-' + yy;
128
- }
129
-
130
- interface Utilities {
131
- parseDate: (date: string) => Date,
132
- sendOKMessage: (res: any, message: any) => any,
133
- getNowDateString: () => {},
134
- sendErrorMessage: (res: any, err: any, tag?: string, status?: number) => any,
135
- sendBaseResponse: (res: any, payload: any) => any,
136
- toCamel: (s: any) => any,
137
- isArray: (a: any) => boolean,
138
- isObject: (o: any) => boolean,
139
- keysToCamel: (o: any) => any,
140
- addStartingZeros: (num: number, totalLength: number) => string,
141
- dateToMoncler: (dData: Date, bAddMs?: boolean) => string,
142
- dateToSql: (dData: Date, bAddMs?: boolean) => string,
143
- dateToSimple: (dData: Date) => string
144
- }
145
-
146
- export const Utilities: Utilities = {
147
- parseDate,
148
- sendOKMessage,
149
- getNowDateString,
150
- sendErrorMessage,
151
- sendBaseResponse,
152
- toCamel,
153
- isArray,
154
- isObject,
155
- keysToCamel,
156
- addStartingZeros,
157
- dateToMoncler,
158
- dateToSql,
159
- dateToSimple
160
- }
161
-
package/tsconfig.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es5",
4
- "module": "commonjs",
5
- "declaration": true,
6
- "outDir": "./dist",
7
- "esModuleInterop": true
8
- },
9
- "include": [
10
- "src/index.ts",
11
- "src/**/*.ts"
12
- ],
13
- "exclude": [
14
- "node_modules"
15
- ]
16
- }
File without changes
File without changes