@pxp-nd/core 1.2.2 → 1.2.3

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.
Files changed (67) hide show
  1. package/README.md +1 -1
  2. package/dist/PxpApp.d.ts +54 -54
  3. package/dist/PxpApp.js +283 -283
  4. package/dist/ScriptManager.d.ts +1 -1
  5. package/dist/ScriptManager.js +130 -130
  6. package/dist/database/script.d.ts +16 -16
  7. package/dist/database/script.js +143 -143
  8. package/dist/db.datasource.d.ts +2 -2
  9. package/dist/db.datasource.js +86 -86
  10. package/dist/entities/Log.d.ts +32 -32
  11. package/dist/entities/Log.js +95 -95
  12. package/dist/entities/ScriptVersion.d.ts +19 -19
  13. package/dist/entities/ScriptVersion.js +43 -43
  14. package/dist/index.d.ts +11 -11
  15. package/dist/index.js +28 -28
  16. package/dist/interfaces.d.ts +44 -44
  17. package/dist/interfaces.js +3 -3
  18. package/dist/lib/pxp/Controller.d.ts +51 -51
  19. package/dist/lib/pxp/Controller.js +378 -371
  20. package/dist/lib/pxp/ControllerInterface.d.ts +18 -18
  21. package/dist/lib/pxp/ControllerInterface.js +2 -2
  22. package/dist/lib/pxp/Decorators.d.ts +23 -19
  23. package/dist/lib/pxp/Decorators.js +123 -125
  24. package/dist/lib/pxp/ListParamInterface.d.ts +23 -23
  25. package/dist/lib/pxp/ListParamInterface.js +2 -2
  26. package/dist/lib/pxp/PxpError.d.ts +24 -24
  27. package/dist/lib/pxp/PxpError.js +57 -57
  28. package/dist/lib/pxp/RouteDefinition.d.ts +26 -26
  29. package/dist/lib/pxp/RouteDefinition.js +26 -26
  30. package/dist/lib/pxp/index.d.ts +20 -20
  31. package/dist/lib/pxp/index.js +33 -33
  32. package/dist/lib/pxp/loadControllers.d.ts +4 -4
  33. package/dist/lib/pxp/loadControllers.js +89 -89
  34. package/dist/lib/pxp/middlewares/ParseParams.d.ts +4 -4
  35. package/dist/lib/pxp/middlewares/ParseParams.js +71 -71
  36. package/dist/lib/pxp/middlewares/isReportMiddleware.d.ts +2 -2
  37. package/dist/lib/pxp/middlewares/isReportMiddleware.js +13 -13
  38. package/dist/lib/pxp/utils/Security.d.ts +23 -23
  39. package/dist/lib/pxp/utils/Security.js +77 -77
  40. package/dist/lib/pxp/utils/crypto.d.ts +3 -3
  41. package/dist/lib/pxp/utils/crypto.js +15 -15
  42. package/dist/lib/reports/fonts/Roboto-Regular-normal.d.ts +2 -2
  43. package/dist/lib/reports/fonts/Roboto-Regular-normal.js +4 -4
  44. package/dist/lib/reports/generated.d.ts +4 -4
  45. package/dist/lib/reports/generated.js +200 -200
  46. package/dist/lib/reports/helper.d.ts +8 -8
  47. package/dist/lib/reports/helper.js +49 -49
  48. package/dist/lib/reports/pdf.d.ts +3 -3
  49. package/dist/lib/reports/pdf.js +119 -119
  50. package/dist/lib/reports/report-routes.d.ts +3 -3
  51. package/dist/lib/reports/report-routes.js +24 -24
  52. package/dist/lib/reports/xlsx.d.ts +1 -1
  53. package/dist/lib/reports/xlsx.js +65 -65
  54. package/dist/sockets/basic-sockets.d.ts +5 -5
  55. package/dist/sockets/basic-sockets.js +38 -38
  56. package/dist/sockets/entities/UserIo.d.ts +6 -6
  57. package/dist/sockets/entities/UserIo.js +30 -30
  58. package/dist/sockets/entities/index.d.ts +5 -5
  59. package/dist/sockets/entities/index.js +9 -9
  60. package/dist/sockets/index.d.ts +2 -2
  61. package/dist/sockets/index.js +19 -19
  62. package/dist/sockets/pxp-io-server.d.ts +6 -6
  63. package/dist/sockets/pxp-io-server.js +50 -50
  64. package/dist/swaggerOptions.d.ts +16 -16
  65. package/dist/swaggerOptions.js +20 -20
  66. package/package.json +65 -64
  67. package/yalc.lock +9 -9
@@ -1,371 +1,378 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
- Object.defineProperty(o, "default", { enumerable: true, value: v });
11
- }) : function(o, v) {
12
- o["default"] = v;
13
- });
14
- var __importStar = (this && this.__importStar) || function (mod) {
15
- if (mod && mod.__esModule) return mod;
16
- var result = {};
17
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
- __setModuleDefault(result, mod);
19
- return result;
20
- };
21
- var __importDefault = (this && this.__importDefault) || function (mod) {
22
- return (mod && mod.__esModule) ? mod : { "default": mod };
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.Controller = void 0;
26
- /**
27
- * Kplian Ltda 2020
28
- *
29
- * MIT
30
- *
31
- * Controller Class.
32
- *
33
- * @summary All common controllers functionality go here (all controllers should inherit this class).
34
- * @author Jaime Rivera
35
- *
36
- * Created at : 2020-06-13 18:09:48
37
- * Last modified : 2020-10-13 15:36:31
38
- * Last modified : 2021-03-10 15:36:31 - Favio Figueroa
39
- * Last modified : 2021-05-01 18:35:31 - Favio Figueroa
40
- */
41
- const typeorm_1 = require("typeorm");
42
- const class_validator_1 = require("class-validator");
43
- const lodash_1 = __importDefault(require("lodash"));
44
- const express_1 = require("express");
45
- const joi_1 = __importDefault(require("joi"));
46
- const RouteDefinition_1 = require("./RouteDefinition");
47
- const index_1 = require("./index");
48
- // import { User } from '@pxp-nd/entities';
49
- // import { isAuthenticated } from '@pxp-nd/auth';
50
- const ParseParams_1 = require("./middlewares/ParseParams");
51
- const isReportMiddleware_1 = require("./middlewares/isReportMiddleware");
52
- const pdf_1 = require("../reports/pdf");
53
- const xlsx_1 = require("../reports/xlsx");
54
- // import * as entities from '@pxp-nd/entities';
55
- // const pxpEntities: any = entities;
56
- class Controller {
57
- constructor(module, Entity = null, config = {
58
- apiPrefix: '/api',
59
- defaultDbSettings: 'Orm',
60
- middlewares: [],
61
- entities: {},
62
- }, io = null) {
63
- this.router = express_1.Router();
64
- this.path = '';
65
- this.module = '';
66
- this.modelString = '';
67
- this.transactionCode = '';
68
- this.user = {}; //User;
69
- this.basicRoutes = [
70
- { requestMethod: RouteDefinition_1.Method.post, path: '/add', methodName: 'add' },
71
- { requestMethod: RouteDefinition_1.Method.delete, path: '/delete/:id', methodName: 'delete' },
72
- { requestMethod: RouteDefinition_1.Method.patch, path: '/edit/:id', methodName: 'edit' },
73
- { requestMethod: RouteDefinition_1.Method.get, path: '/list', methodName: 'list' }
74
- ];
75
- this.basicReadOnly = {
76
- add: false,
77
- edit: false,
78
- list: true,
79
- delete: false
80
- };
81
- this.validated = false;
82
- this.module = module;
83
- this.config = config;
84
- this.io = io;
85
- if (Reflect.hasMetadata('model', this.constructor)) {
86
- this.modelString = Reflect.getMetadata('model', this.constructor);
87
- const [moduleName, entityName] = this.modelString.split('/');
88
- const mainDir = process.cwd();
89
- try {
90
- if (Entity) {
91
- this.model = Entity;
92
- }
93
- else if (config.modules && config.modules[this.module]) {
94
- const moduleExternal = config.modules[this.module];
95
- this.model = moduleExternal.entities[entityName];
96
- }
97
- else {
98
- Promise.resolve().then(() => __importStar(require(`${mainDir}/dist/modules/${moduleName}/entity/${entityName}`))).then((model) => {
99
- this.model = model.default;
100
- });
101
- }
102
- }
103
- catch (_a) {
104
- throw new index_1.PxpError(500, 'Model defined in ' + this.constructor.name + ' not found.');
105
- }
106
- }
107
- this.initializeRoutes();
108
- }
109
- initializeRoutes() {
110
- let routes = Reflect.getMetadata('routes', this.constructor);
111
- this.path = '/' + this.constructor.name;
112
- // get controller path
113
- if (Reflect.hasMetadata('controller_path', this.constructor)) {
114
- this.path = Reflect.getMetadata('controller_path', this.constructor);
115
- }
116
- // get read only
117
- let readonly = Reflect.getMetadata('readonly', this.constructor) || {};
118
- // get authentication
119
- const authentication = Reflect.getMetadata('authentication', this.constructor) || {};
120
- // get permission
121
- const permission = Reflect.getMetadata('permission', this.constructor) || {};
122
- // get log
123
- const log = Reflect.getMetadata('log', this.constructor) || {};
124
- // get dbsettings
125
- const dbsettings = Reflect.getMetadata('dbsettings', this.constructor) || {};
126
- // get logConfig
127
- const logConfig = Reflect.getMetadata('logConfig', this.constructor) || {};
128
- const defaultConfig = Reflect.getMetadata('optionsRoute', this.constructor) || {};
129
- // define basic routes
130
- if (this.modelString !== '') {
131
- routes = lodash_1.default.union(this.basicRoutes, routes);
132
- readonly = Object.assign(Object.assign({}, this.basicReadOnly), readonly);
133
- }
134
- routes.forEach((route) => {
135
- const methodDbSettings = dbsettings[route.methodName] || this.config.defaultDbSettings;
136
- // readOnly
137
- const readOnlyMethod = readonly[route.methodName] !== undefined ? readonly[route.methodName] : defaultConfig[route.methodName].readOnly;
138
- if (readOnlyMethod === null || readOnlyMethod === undefined) {
139
- throw new index_1.PxpError(500, 'ReadOnly decorator was not defined for ' +
140
- route.methodName +
141
- ' in ' +
142
- this.constructor.name +
143
- ' controller.');
144
- }
145
- // auth
146
- const auth = authentication[route.methodName] !== undefined ? authentication[route.methodName] : (defaultConfig[route.methodName] ? defaultConfig[route.methodName].authentication : true);
147
- if (!auth) {
148
- this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
149
- // MIDDLEWARES AREA
150
- [
151
- ParseParams_1.parseParams
152
- ], async (req, res, next) => {
153
- // Execute our method for this path and pass our express request and response object.
154
- // const params = { ...req.query, ...req.body, ...req.params };
155
- const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
156
- this.pxpParams = req.pxpParams;
157
- this.transactionCode = (this.module + this.path + route.path)
158
- .split('/')
159
- .join('.')
160
- .toLowerCase();
161
- this.validated = false;
162
- try {
163
- await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, false, log[route.methodName], logConfig[route.methodName]));
164
- }
165
- catch (ex) {
166
- const now = new Date();
167
- const iniAt = req.start;
168
- const endsAt = now.valueOf() - iniAt.valueOf();
169
- res.logId = await index_1.__(index_1.insertLog('nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
170
- params, ex.stack, ex.statusCode, endsAt, logConfig));
171
- index_1.errorMiddleware(ex, req, res);
172
- }
173
- });
174
- }
175
- else {
176
- this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
177
- // MIDDLEWARES AREA
178
- [
179
- ...this.config.middlewares,
180
- isReportMiddleware_1.isReportMiddleware,
181
- ParseParams_1.parseParams
182
- ], async (req, res, next) => {
183
- // Execute our method for this path and pass our express request and response object.
184
- const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
185
- this.pxpParams = req.pxpParams;
186
- if (req.user) {
187
- // this.user = req.user as User;
188
- this.user = req.user;
189
- }
190
- this.transactionCode = (this.module + this.path + route.path)
191
- .split('/')
192
- .join('.')
193
- .toLowerCase();
194
- this.validated = false;
195
- try {
196
- await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, permission[route.methodName], log[route.methodName], logConfig[route.methodName]));
197
- }
198
- catch (ex) {
199
- const now = new Date();
200
- const iniAt = req.start;
201
- const endsAt = now.valueOf() - iniAt.valueOf();
202
- res.logId = (await index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
203
- params, ex.stack, ex.statusCode, endsAt, logConfig)));
204
- index_1.errorMiddleware(ex, req, res);
205
- }
206
- });
207
- }
208
- });
209
- }
210
- async genericMethodWrapper(params, req, next, res, methodName, dbsettings, readonly, permission = true, log = true, logConfig = {}) {
211
- if (dbsettings === 'Orm') {
212
- await index_1.__(this.ormMethodWrapper(params, req, next, res, methodName, readonly, permission, log, logConfig));
213
- }
214
- else if (dbsettings === 'Procedure') {
215
- await index_1.__(this.procedureMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig));
216
- }
217
- else {
218
- await this.sqlMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig);
219
- }
220
- }
221
- async ormMethodWrapper(params, req, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
222
- let metResponse;
223
- if (permission) {
224
- if (this.user && this.user.roles && this.user.roles.length === 0) {
225
- const hasPermission = await index_1.__(index_1.userHasPermission(this.config.entities.Role)(this.user.userId, this.transactionCode));
226
- if (!hasPermission) {
227
- throw new index_1.PxpError(403, 'Access denied to execute this method');
228
- }
229
- }
230
- }
231
- if (readonly) {
232
- metResponse = await index_1.__(eval(`this.${methodName}(params, res)`));
233
- }
234
- else {
235
- const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
236
- const queryRunner = connection.createQueryRunner();
237
- // establish real database connection using our new query runner
238
- await index_1.__(queryRunner.connect());
239
- await index_1.__(queryRunner.startTransaction());
240
- try {
241
- metResponse = (await eval(`this.${methodName}(params, queryRunner.manager, res)`));
242
- await queryRunner.commitTransaction();
243
- }
244
- catch (err) {
245
- await queryRunner.rollbackTransaction();
246
- throw err;
247
- }
248
- finally {
249
- await index_1.__(queryRunner.release());
250
- }
251
- }
252
- if (log) {
253
- const now = new Date();
254
- const iniAt = req.start;
255
- const endsAt = now.valueOf() - iniAt.valueOf();
256
- index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'success', 'successful transaction', this.module, this.transactionCode, '', params, JSON.stringify(metResponse), '200', endsAt, logConfig));
257
- }
258
- if (req.report && req.report.type === 'pdf') {
259
- req.reportData = metResponse;
260
- pdf_1.makePdf(req, res);
261
- }
262
- else if (req.report && req.report.type === 'xlsx') {
263
- req.reportData = metResponse;
264
- xlsx_1.makeXlsx(req, res);
265
- }
266
- else {
267
- res.json(metResponse);
268
- }
269
- }
270
- async list(params) {
271
- const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
272
- const queryRunner = connection.getMetadata(this.model).ownColumns.find(column => column.isPrimary === true);
273
- // ffp search if in the params has been sent the primary key
274
- const primaryKeyColumn = queryRunner.propertyName;
275
- if (primaryKeyColumn in params) {
276
- const findOne = await index_1.__(this.model.findOne({ where: { [primaryKeyColumn]: params[primaryKeyColumn] } }));
277
- return { data: findOne, count: 1 };
278
- }
279
- // filter by some column that exist in the entity
280
- // ffp if some column is into of params for added in the condition
281
- let ownColumnsForSchema = {};
282
- const whereOwnColumns = connection.getMetadata(this.model).ownColumns.reduce((t, column) => {
283
- if (`_${column.propertyName}` in params) {
284
- ownColumnsForSchema = Object.assign(Object.assign({}, ownColumnsForSchema), { [`_${column.propertyName}`]: joi_1.default.string() });
285
- t = Object.assign(Object.assign({}, t), { [column.propertyName]: params[`_${column.propertyName}`] });
286
- }
287
- return t;
288
- }, {});
289
- const schema = this.getListSchema(ownColumnsForSchema);
290
- const resParams = await index_1.__(this.schemaValidate(schema, params));
291
- const listParam = this.getListParams(resParams, whereOwnColumns);
292
- const [rows, count] = await index_1.__(this.model.findAndCount(listParam));
293
- return { data: rows, count };
294
- }
295
- async add(params, manager) {
296
- const modelInstance = new this.model();
297
- Object.assign(modelInstance, params);
298
- modelInstance.createdBy = this.user ? this.user.username : '_';
299
- await index_1.__(this.classValidate(modelInstance));
300
- await manager.save(modelInstance);
301
- return modelInstance;
302
- }
303
- async edit(params, manager) {
304
- const modelInstance = (await index_1.__(this.model.findOne(params.id)));
305
- if (!modelInstance) {
306
- throw new index_1.PxpError(406, 'Record not found');
307
- }
308
- const editParams = params;
309
- Object.assign(modelInstance, editParams);
310
- delete editParams.id;
311
- modelInstance.modifiedBy = this.user ? this.user.username : null;
312
- await index_1.__(this.classValidate(modelInstance));
313
- await manager.save(modelInstance);
314
- return modelInstance;
315
- }
316
- async delete(params, manager) {
317
- const modelInstance = (await index_1.__(this.model.findOne(params.id)));
318
- if (!modelInstance) {
319
- throw new index_1.PxpError(406, 'Record not found');
320
- }
321
- await manager.remove(modelInstance);
322
- return modelInstance;
323
- }
324
- getListParams(params, where) {
325
- const whereGenericFilter = [];
326
- if (params.genericFilterFields) {
327
- const genericFilterFields = params.genericFilterFields;
328
- const filterFieldsArray = genericFilterFields.split('#');
329
- filterFieldsArray.forEach((field) => {
330
- whereGenericFilter.push(Object.assign({ [field]: typeorm_1.Like('%' + params.genericFilterValue + '%') }, where));
331
- });
332
- }
333
- const res = {
334
- where: whereGenericFilter.length > 0 ? whereGenericFilter : [where],
335
- skip: params.start,
336
- take: params.limit,
337
- order: {
338
- [params.sort]: String(params.dir).toUpperCase()
339
- }
340
- };
341
- // ffp search if in this request is sending the id
342
- return res;
343
- }
344
- async procedureMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
345
- console.log('before function');
346
- await eval(`this.${methodName}(req, res)`);
347
- console.log('after function');
348
- }
349
- async sqlMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
350
- console.log('before function');
351
- await eval(`this.${methodName}(req, res)`);
352
- console.log('after function');
353
- }
354
- async classValidate(model) {
355
- const errors = await index_1.__(class_validator_1.validate(model));
356
- this.validated = true;
357
- if (errors.length > 0) {
358
- throw new index_1.PxpError(406, 'Validation failed!', errors);
359
- }
360
- }
361
- async schemaValidate(schema, params) {
362
- const value = await index_1.__(schema.validateAsync(params, { abortEarly: false }), true);
363
- this.validated = true;
364
- return value;
365
- }
366
- getListSchema(ownColumns) {
367
- const schema = joi_1.default.object(Object.assign({ start: joi_1.default.number().integer().required(), limit: joi_1.default.number().integer().positive().required(), sort: joi_1.default.string().min(2).required(), dir: joi_1.default.string().min(3).max(4).required(), genericFilterFields: joi_1.default.string().min(2), genericFilterValue: joi_1.default.string().min(1) }, ownColumns));
368
- return schema;
369
- }
370
- }
371
- exports.Controller = Controller;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.Controller = void 0;
26
+ /**
27
+ * Kplian Ltda 2020
28
+ *
29
+ * MIT
30
+ *
31
+ * Controller Class.
32
+ *
33
+ * @summary All common controllers functionality go here (all controllers should inherit this class).
34
+ * @author Jaime Rivera
35
+ *
36
+ * Created at : 2020-06-13 18:09:48
37
+ * Last modified : 2020-10-13 15:36:31
38
+ * Last modified : 2021-03-10 15:36:31 - Favio Figueroa
39
+ * Last modified : 2021-05-01 18:35:31 - Favio Figueroa
40
+ */
41
+ const typeorm_1 = require("typeorm");
42
+ const class_validator_1 = require("class-validator");
43
+ const lodash_1 = __importDefault(require("lodash"));
44
+ const express_1 = require("express");
45
+ const joi_1 = __importDefault(require("joi"));
46
+ const RouteDefinition_1 = require("./RouteDefinition");
47
+ const index_1 = require("./index");
48
+ // import { User } from '@pxp-nd/entities';
49
+ // import { isAuthenticated } from '@pxp-nd/auth';
50
+ const ParseParams_1 = require("./middlewares/ParseParams");
51
+ const isReportMiddleware_1 = require("./middlewares/isReportMiddleware");
52
+ const pdf_1 = require("../reports/pdf");
53
+ const xlsx_1 = require("../reports/xlsx");
54
+ // import * as entities from '@pxp-nd/entities';
55
+ // const pxpEntities: any = entities;
56
+ class Controller {
57
+ constructor(module, Entity = null, config = {
58
+ apiPrefix: '/api',
59
+ defaultDbSettings: 'Orm',
60
+ middlewares: [],
61
+ entities: {},
62
+ }, io = null) {
63
+ this.router = express_1.Router();
64
+ this.path = '';
65
+ this.module = '';
66
+ this.modelString = '';
67
+ this.transactionCode = '';
68
+ this.user = {}; //User;
69
+ this.basicRoutes = [
70
+ { requestMethod: RouteDefinition_1.Method.post, path: '/add', methodName: 'add' },
71
+ { requestMethod: RouteDefinition_1.Method.delete, path: '/delete/:id', methodName: 'delete' },
72
+ { requestMethod: RouteDefinition_1.Method.patch, path: '/edit/:id', methodName: 'edit' },
73
+ { requestMethod: RouteDefinition_1.Method.get, path: '/list', methodName: 'list' }
74
+ ];
75
+ this.basicReadOnly = {
76
+ add: false,
77
+ edit: false,
78
+ list: true,
79
+ delete: false
80
+ };
81
+ this.validated = false;
82
+ this.module = module;
83
+ this.config = config;
84
+ this.io = io;
85
+ if (Reflect.hasMetadata('model', this.constructor)) {
86
+ this.modelString = Reflect.getMetadata('model', this.constructor);
87
+ const [moduleName, entityName] = this.modelString.split('/');
88
+ const mainDir = process.cwd();
89
+ try {
90
+ if (Entity) {
91
+ this.model = Entity;
92
+ }
93
+ else if (config.modules && config.modules[this.module]) {
94
+ const moduleExternal = config.modules[this.module];
95
+ this.model = moduleExternal.entities[entityName];
96
+ }
97
+ else {
98
+ Promise.resolve().then(() => __importStar(require(`${mainDir}/dist/modules/${moduleName}/entity/${entityName}`))).then((model) => {
99
+ this.model = model.default;
100
+ });
101
+ }
102
+ }
103
+ catch (_a) {
104
+ throw new index_1.PxpError(500, 'Model defined in ' + this.constructor.name + ' not found.');
105
+ }
106
+ }
107
+ this.initializeRoutes();
108
+ }
109
+ initializeRoutes() {
110
+ let routes = Reflect.getMetadata('routes', this.constructor);
111
+ this.path = '/' + this.constructor.name;
112
+ // get controller path
113
+ if (Reflect.hasMetadata('controller_path', this.constructor)) {
114
+ this.path = Reflect.getMetadata('controller_path', this.constructor);
115
+ }
116
+ // get read only
117
+ let readonly = Reflect.getMetadata('readonly', this.constructor) || {};
118
+ // get authentication
119
+ const authentication = Reflect.getMetadata('authentication', this.constructor) || {};
120
+ // get permission
121
+ const permission = Reflect.getMetadata('permission', this.constructor) || {};
122
+ // get log
123
+ const log = Reflect.getMetadata('log', this.constructor) || {};
124
+ console.log('qqqqqqw', log);
125
+ // get dbsettings
126
+ const dbsettings = Reflect.getMetadata('dbsettings', this.constructor) || {};
127
+ // get logConfig
128
+ const logConfig = Reflect.getMetadata('logConfig', this.constructor) || {};
129
+ const defaultConfig = Reflect.getMetadata('optionsRoute', this.constructor) || {};
130
+ // define basic routes
131
+ if (this.modelString !== '') {
132
+ routes = lodash_1.default.union(this.basicRoutes, routes);
133
+ readonly = Object.assign(Object.assign({}, this.basicReadOnly), readonly);
134
+ }
135
+ routes.forEach((route) => {
136
+ const methodDbSettings = dbsettings[route.methodName] || this.config.defaultDbSettings;
137
+ // readOnly
138
+ const readOnlyMethod = readonly[route.methodName] !== undefined ? readonly[route.methodName] : defaultConfig[route.methodName].readOnly;
139
+ // log
140
+ const logMethod = log[route.methodName] !== undefined ? log[route.methodName] : (defaultConfig[route.methodName] ? defaultConfig[route.methodName].log : true);
141
+ const logValue = typeof logMethod == 'object' ? logMethod : logConfig[route.methodName];
142
+ const logKey = typeof logMethod == 'object' ? true : logMethod;
143
+ if (readOnlyMethod === null || readOnlyMethod === undefined) {
144
+ throw new index_1.PxpError(500, 'ReadOnly decorator was not defined for ' +
145
+ route.methodName +
146
+ ' in ' +
147
+ this.constructor.name +
148
+ ' controller.');
149
+ }
150
+ // auth
151
+ const auth = authentication[route.methodName] !== undefined ? authentication[route.methodName] : (defaultConfig[route.methodName] ? defaultConfig[route.methodName].authentication : true);
152
+ if (!auth) {
153
+ this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
154
+ // MIDDLEWARES AREA
155
+ [
156
+ ParseParams_1.parseParams
157
+ ], async (req, res, next) => {
158
+ // Execute our method for this path and pass our express request and response object.
159
+ // const params = { ...req.query, ...req.body, ...req.params };
160
+ const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
161
+ this.pxpParams = req.pxpParams;
162
+ this.transactionCode = (this.module + this.path + route.path)
163
+ .split('/')
164
+ .join('.')
165
+ .toLowerCase();
166
+ this.validated = false;
167
+ try {
168
+ await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, false, logKey, logValue));
169
+ }
170
+ catch (ex) {
171
+ const now = new Date();
172
+ const iniAt = req.start;
173
+ const endsAt = now.valueOf() - iniAt.valueOf();
174
+ res.logId = await index_1.__(index_1.insertLog('nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
175
+ params, ex.stack, ex.statusCode, endsAt, logConfig));
176
+ index_1.errorMiddleware(ex, req, res);
177
+ }
178
+ });
179
+ }
180
+ else {
181
+ //NORMALMENTE VIENE POR AQUI RCM-20211011 *****
182
+ this.router[route.requestMethod](this.config.apiPrefix + '/' + this.module + this.path + route.path,
183
+ // MIDDLEWARES AREA
184
+ [
185
+ ...this.config.middlewares,
186
+ isReportMiddleware_1.isReportMiddleware,
187
+ ParseParams_1.parseParams
188
+ ], async (req, res, next) => {
189
+ // Execute our method for this path and pass our express request and response object.
190
+ const params = Object.assign(Object.assign({}, req.files), req.paramasMerge);
191
+ this.pxpParams = req.pxpParams;
192
+ if (req.user) {
193
+ // this.user = req.user as User;
194
+ this.user = req.user;
195
+ }
196
+ this.transactionCode = (this.module + this.path + route.path)
197
+ .split('/')
198
+ .join('.')
199
+ .toLowerCase();
200
+ this.validated = false;
201
+ try {
202
+ await index_1.__(this.genericMethodWrapper(params, req, next, res, route.methodName, methodDbSettings, readOnlyMethod, permission[route.methodName], logKey, logValue));
203
+ }
204
+ catch (ex) {
205
+ const now = new Date();
206
+ const iniAt = req.start;
207
+ const endsAt = now.valueOf() - iniAt.valueOf();
208
+ res.logId = (await index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'error', ex.tecMessage, this.module, this.transactionCode, '', // query
209
+ params, ex.stack, ex.statusCode, endsAt, Object.assign(Object.assign({}, logConfig), { logValue }))));
210
+ index_1.errorMiddleware(ex, req, res);
211
+ }
212
+ });
213
+ }
214
+ });
215
+ }
216
+ async genericMethodWrapper(params, req, next, res, methodName, dbsettings, readonly, permission = true, log = true, logConfig = {}) {
217
+ if (dbsettings === 'Orm') {
218
+ await index_1.__(this.ormMethodWrapper(params, req, next, res, methodName, readonly, permission, log, logConfig));
219
+ }
220
+ else if (dbsettings === 'Procedure') {
221
+ await index_1.__(this.procedureMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig));
222
+ }
223
+ else {
224
+ await this.sqlMethodWrapper(params, next, res, methodName, readonly, permission, log, logConfig);
225
+ }
226
+ }
227
+ async ormMethodWrapper(params, req, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
228
+ let metResponse;
229
+ if (permission) {
230
+ if (this.user && this.user.roles && this.user.roles.length === 0) {
231
+ const hasPermission = await index_1.__(index_1.userHasPermission(this.config.entities.Role)(this.user.userId, this.transactionCode));
232
+ if (!hasPermission) {
233
+ throw new index_1.PxpError(403, 'Access denied to execute this method');
234
+ }
235
+ }
236
+ }
237
+ if (readonly) {
238
+ metResponse = await index_1.__(eval(`this.${methodName}(params, res)`));
239
+ }
240
+ else {
241
+ const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
242
+ const queryRunner = connection.createQueryRunner();
243
+ // establish real database connection using our new query runner
244
+ await index_1.__(queryRunner.connect());
245
+ await index_1.__(queryRunner.startTransaction());
246
+ try {
247
+ metResponse = (await eval(`this.${methodName}(params, queryRunner.manager, res)`));
248
+ await queryRunner.commitTransaction();
249
+ }
250
+ catch (err) {
251
+ await queryRunner.rollbackTransaction();
252
+ throw err;
253
+ }
254
+ finally {
255
+ await index_1.__(queryRunner.release());
256
+ }
257
+ }
258
+ if (log) {
259
+ const now = new Date();
260
+ const iniAt = req.start;
261
+ const endsAt = now.valueOf() - iniAt.valueOf();
262
+ index_1.__(index_1.insertLog(this.user && this.user.username ? this.user.username : 'nouser', 'mac', req.ip, 'success', 'successful transaction', this.module, this.transactionCode, '', params, JSON.stringify(metResponse), '200', endsAt, logConfig));
263
+ }
264
+ //PARA REPORTES
265
+ if (req.report && req.report.type === 'pdf') {
266
+ req.reportData = metResponse;
267
+ pdf_1.makePdf(req, res);
268
+ }
269
+ else if (req.report && req.report.type === 'xlsx') {
270
+ req.reportData = metResponse;
271
+ xlsx_1.makeXlsx(req, res);
272
+ }
273
+ else {
274
+ res.json(metResponse);
275
+ }
276
+ }
277
+ async list(params) {
278
+ const connection = typeorm_1.getConnection(process.env.DB_WRITE_CONNECTION_NAME);
279
+ const queryRunner = connection.getMetadata(this.model).ownColumns.find(column => column.isPrimary === true);
280
+ // ffp search if in the params has been sent the primary key
281
+ const primaryKeyColumn = queryRunner.propertyName;
282
+ if (primaryKeyColumn in params) {
283
+ const findOne = await index_1.__(this.model.findOne({ where: { [primaryKeyColumn]: params[primaryKeyColumn] } }));
284
+ return { data: findOne, count: 1 };
285
+ }
286
+ // filter by some column that exist in the entity
287
+ // ffp if some column is into of params for added in the condition
288
+ let ownColumnsForSchema = {};
289
+ const whereOwnColumns = connection.getMetadata(this.model).ownColumns.reduce((t, column) => {
290
+ if (`_${column.propertyName}` in params) {
291
+ ownColumnsForSchema = Object.assign(Object.assign({}, ownColumnsForSchema), { [`_${column.propertyName}`]: joi_1.default.string() });
292
+ t = Object.assign(Object.assign({}, t), { [column.propertyName]: params[`_${column.propertyName}`] });
293
+ }
294
+ return t;
295
+ }, {});
296
+ const schema = this.getListSchema(ownColumnsForSchema);
297
+ const resParams = await index_1.__(this.schemaValidate(schema, params));
298
+ const listParam = this.getListParams(resParams, whereOwnColumns);
299
+ const [rows, count] = await index_1.__(this.model.findAndCount(listParam));
300
+ return { data: rows, count };
301
+ }
302
+ async add(params, manager) {
303
+ const modelInstance = new this.model();
304
+ Object.assign(modelInstance, params);
305
+ modelInstance.createdBy = this.user ? this.user.username : '_';
306
+ await index_1.__(this.classValidate(modelInstance));
307
+ await manager.save(modelInstance);
308
+ return modelInstance;
309
+ }
310
+ async edit(params, manager) {
311
+ const modelInstance = (await index_1.__(this.model.findOne(params.id)));
312
+ if (!modelInstance) {
313
+ throw new index_1.PxpError(406, 'Record not found');
314
+ }
315
+ const editParams = params;
316
+ Object.assign(modelInstance, editParams);
317
+ delete editParams.id;
318
+ modelInstance.modifiedBy = this.user ? this.user.username : null;
319
+ await index_1.__(this.classValidate(modelInstance));
320
+ await manager.save(modelInstance);
321
+ return modelInstance;
322
+ }
323
+ async delete(params, manager) {
324
+ const modelInstance = (await index_1.__(this.model.findOne(params.id)));
325
+ if (!modelInstance) {
326
+ throw new index_1.PxpError(406, 'Record not found');
327
+ }
328
+ await manager.remove(modelInstance);
329
+ return modelInstance;
330
+ }
331
+ getListParams(params, where) {
332
+ const whereGenericFilter = [];
333
+ if (params.genericFilterFields) {
334
+ const genericFilterFields = params.genericFilterFields;
335
+ const filterFieldsArray = genericFilterFields.split('#');
336
+ filterFieldsArray.forEach((field) => {
337
+ whereGenericFilter.push(Object.assign({ [field]: typeorm_1.Like('%' + params.genericFilterValue + '%') }, where));
338
+ });
339
+ }
340
+ const res = {
341
+ where: whereGenericFilter.length > 0 ? whereGenericFilter : [where],
342
+ skip: params.start,
343
+ take: params.limit,
344
+ order: {
345
+ [params.sort]: String(params.dir).toUpperCase()
346
+ }
347
+ };
348
+ // ffp search if in this request is sending the id
349
+ return res;
350
+ }
351
+ async procedureMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
352
+ console.log('before function');
353
+ await eval(`this.${methodName}(req, res)`);
354
+ console.log('after function');
355
+ }
356
+ async sqlMethodWrapper(params, next, res, methodName, readonly, permission = true, log = true, logConfig = {}) {
357
+ console.log('before function');
358
+ await eval(`this.${methodName}(req, res)`);
359
+ console.log('after function');
360
+ }
361
+ async classValidate(model) {
362
+ const errors = await index_1.__(class_validator_1.validate(model));
363
+ this.validated = true;
364
+ if (errors.length > 0) {
365
+ throw new index_1.PxpError(406, 'Validation failed!', errors);
366
+ }
367
+ }
368
+ async schemaValidate(schema, params) {
369
+ const value = await index_1.__(schema.validateAsync(params, { abortEarly: false }), true);
370
+ this.validated = true;
371
+ return value;
372
+ }
373
+ getListSchema(ownColumns) {
374
+ const schema = joi_1.default.object(Object.assign({ start: joi_1.default.number().integer().required(), limit: joi_1.default.number().integer().positive().required(), sort: joi_1.default.string().min(2).required(), dir: joi_1.default.string().min(3).max(4).required(), genericFilterFields: joi_1.default.string().min(2), genericFilterValue: joi_1.default.string().min(1) }, ownColumns));
375
+ return schema;
376
+ }
377
+ }
378
+ exports.Controller = Controller;