@sdflc/backend-helpers 1.0.63 → 1.0.64

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,12 +1,17 @@
1
+ import { Logger } from '@sdflc/utils';
1
2
  /**
2
3
  * Base class for REST API controllers.
3
4
  */
4
5
  declare class BaseController {
6
+ protected onResponse: any;
7
+ protected logger: Logger;
8
+ constructor(props: any);
9
+ init(props: any): void;
5
10
  /**
6
11
  * Executes an action method and returns result in consistent way.
7
12
  * @param method a function to be executed
8
13
  * @returns HTTP response
9
14
  */
10
- json(method: any): (req: any, res: any, next: any) => Promise<any>;
15
+ json(method: any): (req: any, res: any, next: any) => Promise<void>;
11
16
  }
12
17
  export { BaseController };
@@ -8,13 +8,34 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
15
  exports.BaseController = void 0;
16
+ const check_types_1 = __importDefault(require("check-types"));
13
17
  const api_helpers_1 = require("@sdflc/api-helpers");
18
+ const utils_1 = require("@sdflc/utils");
14
19
  /**
15
20
  * Base class for REST API controllers.
16
21
  */
17
22
  class BaseController {
23
+ constructor(props) {
24
+ if (check_types_1.default.function(props === null || props === void 0 ? void 0 : props.onResponse)) {
25
+ this.onResponse = props === null || props === void 0 ? void 0 : props.onResponse;
26
+ }
27
+ else {
28
+ this.onResponse = () => {
29
+ /* TODO */
30
+ };
31
+ }
32
+ this.logger = props.logger instanceof utils_1.Logger ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.LOG });
33
+ }
34
+ init(props) {
35
+ // const { app } = props;
36
+ // set express app routes here:
37
+ // app.post(`${root}/event-webhook`, this.json(this.eventWebhook));
38
+ }
18
39
  /**
19
40
  * Executes an action method and returns result in consistent way.
20
41
  * @param method a function to be executed
@@ -22,17 +43,23 @@ class BaseController {
22
43
  */
23
44
  json(method) {
24
45
  return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
46
+ var _a, _b;
25
47
  try {
26
- const r = yield method(req, res, next);
27
- if (r instanceof api_helpers_1.OpResult) {
28
- return res.status(r.getHttpStatus()).json(r.toJS());
48
+ const result = yield method(req, res, next);
49
+ if (result instanceof api_helpers_1.OpResult) {
50
+ res.status(result.getHttpStatus()).json(result.toJS());
29
51
  }
30
- else if (r) {
31
- return res.json(r);
52
+ else if (result) {
53
+ res.json(result);
32
54
  }
33
55
  else {
34
- return res.status(204).json(new api_helpers_1.OpResult());
56
+ res.status(204).json(new api_helpers_1.OpResult());
57
+ }
58
+ if (((_a = req.context) === null || _a === void 0 ? void 0 : _a.isExternalDb) === false && ((_b = req.context) === null || _b === void 0 ? void 0 : _b.db)) {
59
+ this.logger.log('Release DB connection');
60
+ req.context.db.destroy();
35
61
  }
62
+ yield this.onResponse(req, res, next);
36
63
  }
37
64
  catch (ex) {
38
65
  next(ex);
@@ -18,7 +18,7 @@ declare class BaseCore {
18
18
  success(data: any, code?: number): any;
19
19
  failure(code: number, errorMsg: string, data?: any): any;
20
20
  validationFailure(ex: OpResult | any): any;
21
- exceptionFailure(ex: any, doingWhat: string | any, data?: any): any;
21
+ exceptionFailure(ex: any, doingWhat: string, data?: any): any;
22
22
  checkResult(args: any): Promise<void>;
23
23
  runAction(opt: CoreActionInterface): Promise<any>;
24
24
  list(args: any): Promise<any>;
@@ -68,7 +68,7 @@ declare class BaseCore {
68
68
  afterRemove(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
69
69
  beforeRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
70
70
  afterRemoveMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
71
- onException(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
71
+ onException(params: any, opt?: BaseCoreActionsInterface): Promise<string | null | undefined>;
72
72
  /**
73
73
  * Returns JWT secret and its settings to verify received JWT token
74
74
  * @param params Object of parameters passed to the authenticate method
package/build/BaseCore.js CHANGED
@@ -8,10 +8,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
15
  exports.BaseCore = void 0;
13
16
  const api_helpers_1 = require("@sdflc/api-helpers");
14
17
  const utils_1 = require("@sdflc/utils");
18
+ const check_types_1 = __importDefault(require("check-types"));
15
19
  const lodash_1 = require("lodash");
16
20
  const commonValidators_1 = require("./commonValidators");
17
21
  const constants_1 = require("./constants");
@@ -114,12 +118,7 @@ class BaseCore {
114
118
  msg = dbErrorMsg;
115
119
  }
116
120
  else {
117
- if (doingWhat['message']) {
118
- msg = doingWhat['message'];
119
- }
120
- else {
121
- msg = isOpResult ? ex.getErrorSummary() : `Sorry, something went wrong on ${doingWhat}`;
122
- }
121
+ msg = isOpResult ? ex.getErrorSummary() : `Sorry, something went wrong on ${doingWhat}`;
123
122
  this.logger.error(sysMsg, ex);
124
123
  }
125
124
  const result = new api_helpers_1.OpResult({ data });
@@ -144,7 +143,7 @@ class BaseCore {
144
143
  }
145
144
  runAction(opt) {
146
145
  return __awaiter(this, void 0, void 0, function* () {
147
- const { args, validate, doAuth, action, hasTransaction, doingWhat } = opt || {};
146
+ const { args, validate, doAuth, action, hasTransaction, doingWhat, onException } = opt || {};
148
147
  // If we process action with the same requestId as requestId passed to the constructor it means
149
148
  // we are processing the same request from FE and can skip some of the operations like transactions and etc
150
149
  const sameRequest = !!this.config.context.requestId && (args === null || args === void 0 ? void 0 : args.requestId) === this.config.context.requestId;
@@ -224,16 +223,25 @@ class BaseCore {
224
223
  if (!sameRequest && hasTransaction) {
225
224
  yield this.getDb().rollbackTransaction();
226
225
  }
227
- yield this.onException(args, Object.assign(Object.assign({}, actionOpt), { doingWhat, exception: ex }));
228
- let what = doingWhat;
226
+ let errMessage = '';
227
+ try {
228
+ errMessage = yield this.onException(args, Object.assign(Object.assign({}, actionOpt), { doingWhat, exception: ex }));
229
+ if (check_types_1.default.function(onException)) {
230
+ errMessage = yield onException(args, Object.assign(Object.assign({}, actionOpt), { doingWhat, exception: ex }));
231
+ }
232
+ }
233
+ catch (ex2) {
234
+ this.logger.log(`An exception has occured when handling exception:`, ex2);
235
+ }
236
+ if (!errMessage) {
237
+ errMessage = doingWhat;
238
+ }
229
239
  if (doingWhat !== step) {
230
- what = {
231
- message: `${step} failed on ${doingWhat}`,
232
- };
240
+ errMessage = `${step} failed on ${doingWhat}`;
233
241
  }
234
242
  const time = this.measureTool.stop(doingWhat);
235
243
  this.logger.debug(`The ${time.name} process time is ${time.durationMs} ms`);
236
- return this.exceptionFailure(ex, what);
244
+ return this.exceptionFailure(ex, errMessage);
237
245
  }
238
246
  });
239
247
  }
@@ -588,7 +596,7 @@ class BaseCore {
588
596
  }
589
597
  onException(params, opt) {
590
598
  return __awaiter(this, void 0, void 0, function* () {
591
- return this.defaultAfterAndBefore(params, opt);
599
+ return '';
592
600
  });
593
601
  }
594
602
  /**
@@ -8,10 +8,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
15
  exports.createContextDefault = exports.createApiContext = void 0;
13
16
  const lodash_1 = require("lodash");
14
17
  const uuid_1 = require("uuid");
18
+ const check_types_1 = __importDefault(require("check-types"));
15
19
  const utils_1 = require("@sdflc/utils");
16
20
  const Database_1 = require("./Database");
17
21
  const constants_1 = require("./constants");
@@ -22,8 +26,8 @@ const constants_1 = require("./constants");
22
26
  const createApiContext = (args) => __awaiter(void 0, void 0, void 0, function* () {
23
27
  const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
24
28
  const requestId = inRequestId || (0, uuid_1.v4)();
25
- const coreContext = typeof getCoreContext === 'function' ? yield getCoreContext({ req }) : {};
26
- const gatewayContext = typeof getGatewayContext === 'function' ? yield getGatewayContext({ req }) : {};
29
+ const coreContext = check_types_1.default.function(getCoreContext) ? yield getCoreContext({ req }) : {};
30
+ const gatewayContext = check_types_1.default.function(getGatewayContext) ? yield getGatewayContext({ req }) : {};
27
31
  const context = {
28
32
  requestId,
29
33
  cores: {},
@@ -40,7 +44,7 @@ const createApiContext = (args) => __awaiter(void 0, void 0, void 0, function* (
40
44
  acc[(0, lodash_1.camelCase)(key)] = new gateways[key](Object.assign(Object.assign({}, gatewayContext), { context }));
41
45
  return acc;
42
46
  }, {});
43
- if (typeof extendContext === 'function') {
47
+ if (check_types_1.default.function(extendContext)) {
44
48
  yield extendContext({ context, req });
45
49
  }
46
50
  return context;
@@ -51,7 +55,7 @@ exports.createApiContext = createApiContext;
51
55
  * @returns {object} A context object with all available cores
52
56
  */
53
57
  const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, function* () {
54
- const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, } = args || {};
58
+ const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
55
59
  const headers = req.headers || { noHeadersSetup: true };
56
60
  const cookies = req.cookies || { noCookiesSetup: true };
57
61
  const authorization = (headers[constants_1.HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
@@ -69,10 +73,12 @@ const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, functio
69
73
  // const roleId = headers[HEADERS.ROLE_ID];
70
74
  // const userId = headers[HEADERS.USER_ID];
71
75
  const requestId = (0, uuid_1.v4)();
72
- const db = new Database_1.Database({
73
- knexConfig,
74
- dbSchema,
75
- });
76
+ const db = inDb
77
+ ? inDb
78
+ : new Database_1.Database({
79
+ knexConfig,
80
+ dbSchema,
81
+ });
76
82
  const sharedContext = {
77
83
  spaceId,
78
84
  apiKey,
@@ -93,6 +99,7 @@ const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, functio
93
99
  headers,
94
100
  cookies,
95
101
  authorizationToken,
102
+ isExternalDb: !!inDb,
96
103
  };
97
104
  return yield (0, exports.createApiContext)({
98
105
  cores,
@@ -103,14 +110,14 @@ const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, functio
103
110
  extendContext: ({ context, req }) => __awaiter(void 0, void 0, void 0, function* () {
104
111
  context.db = db;
105
112
  Object.assign(context, sharedContext);
106
- if (typeof extendContext === 'function') {
113
+ if (check_types_1.default.function(extendContext)) {
107
114
  yield extendContext({ context, req });
108
115
  }
109
116
  }),
110
117
  getCoreContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
111
118
  // TODO: const { req } = args;
112
119
  let extendCoreConext = {};
113
- if (typeof getCoreContext === 'function') {
120
+ if (check_types_1.default.function(getCoreContext)) {
114
121
  extendCoreConext = yield getCoreContext(args);
115
122
  }
116
123
  return Object.assign({ db, gatewayName: '', isProduction,
@@ -123,7 +130,7 @@ const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, functio
123
130
  }),
124
131
  getGatewayContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
125
132
  let extendGatewayConext = {};
126
- if (typeof getGatewayContext === 'function') {
133
+ if (check_types_1.default.function(getGatewayContext)) {
127
134
  extendGatewayConext = yield getGatewayContext(args);
128
135
  }
129
136
  return Object.assign({ db,
@@ -13,4 +13,6 @@ declare enum ID_TYPES {
13
13
  declare const ID_FIELD: any;
14
14
  declare const DEFAULT_ORDER_NO = "10000000";
15
15
  declare const DEFAULT_ORDER_NO_STEP = "1000";
16
- export { ID_FIELD, FIELDS, ORDER_BYS, HEADERS, DEFAULT_ORDER_NO, DEFAULT_ORDER_NO_STEP, ID_TYPES };
16
+ declare const DEFAULT_JWT_ALGORITHM = "HS256";
17
+ declare const DEFAULT_JWT_ISSUER = "microservices-auth";
18
+ export { ID_FIELD, FIELDS, ORDER_BYS, HEADERS, DEFAULT_ORDER_NO, DEFAULT_ORDER_NO_STEP, ID_TYPES, DEFAULT_JWT_ALGORITHM, DEFAULT_JWT_ISSUER, };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ID_TYPES = exports.DEFAULT_ORDER_NO_STEP = exports.DEFAULT_ORDER_NO = exports.HEADERS = exports.ORDER_BYS = exports.FIELDS = exports.ID_FIELD = void 0;
3
+ exports.DEFAULT_JWT_ISSUER = exports.DEFAULT_JWT_ALGORITHM = exports.ID_TYPES = exports.DEFAULT_ORDER_NO_STEP = exports.DEFAULT_ORDER_NO = exports.HEADERS = exports.ORDER_BYS = exports.FIELDS = exports.ID_FIELD = void 0;
4
4
  const FIELDS = {
5
5
  ID: 'id',
6
6
  STATUS: 'status',
@@ -62,3 +62,7 @@ const DEFAULT_ORDER_NO = '10000000';
62
62
  exports.DEFAULT_ORDER_NO = DEFAULT_ORDER_NO;
63
63
  const DEFAULT_ORDER_NO_STEP = '1000';
64
64
  exports.DEFAULT_ORDER_NO_STEP = DEFAULT_ORDER_NO_STEP;
65
+ const DEFAULT_JWT_ALGORITHM = 'HS256';
66
+ exports.DEFAULT_JWT_ALGORITHM = DEFAULT_JWT_ALGORITHM;
67
+ const DEFAULT_JWT_ISSUER = 'microservices-auth';
68
+ exports.DEFAULT_JWT_ISSUER = DEFAULT_JWT_ISSUER;
@@ -7,4 +7,5 @@ export interface CoreActionInterface {
7
7
  action(args?: any, opt?: any): any;
8
8
  hasTransaction: boolean;
9
9
  doingWhat?: string;
10
+ onException?(params: any, opt?: BaseCoreActionsInterface): Promise<any | undefined | null>;
10
11
  }
@@ -18,7 +18,7 @@ const camelResponse = (result) => {
18
18
  return (0, utils_1.camelKeys)(result);
19
19
  };
20
20
  const buildKnexConfig = (dirName, appConfig) => {
21
- const { dbType, dbHost, dbPort, dbName, dbSchema, dbUser, dbPassword, debug, nodeEnv, migrationsTemplateFileName, migrationsFolder, migrationsTable, useSchemaForMigrationsTable, seedsFolder, seedsFolderDev, seedsFolderProd, wrapIdentifierOverrideMap, } = appConfig;
21
+ const { dbType, dbHost, dbPort, dbName, dbSchema, dbUser, dbPassword, debug, nodeEnv, migrationsTemplateFileName, migrationsFolder, migrationsTable, useSchemaForMigrationsTable, seedsFolder, seedsFolderDev, seedsFolderProd, wrapIdentifierOverrideMap, dbPool, } = appConfig;
22
22
  const sharedConfig = {
23
23
  client: dbType || 'pg',
24
24
  postProcessResponse: camelResponse,
@@ -38,6 +38,22 @@ const buildKnexConfig = (dirName, appConfig) => {
38
38
  //ssl: database.ssl,
39
39
  },
40
40
  };
41
+ if (typeof dbPool === 'object') {
42
+ sharedConfig.pool = dbPool;
43
+ }
44
+ else {
45
+ sharedConfig.pool = {
46
+ min: 0,
47
+ max: 50,
48
+ acquireTimeoutMillis: 30000,
49
+ createTimeoutMillis: 30000,
50
+ destroyTimeoutMillis: 5000,
51
+ idleTimeoutMillis: 30000,
52
+ reapIntervalMillis: 1000,
53
+ createRetryIntervalMillis: 200,
54
+ propagateCreateError: false,
55
+ };
56
+ }
41
57
  const config = {
42
58
  development: Object.assign(Object.assign({}, sharedConfig), { debug, migrations: {
43
59
  stub: path_1.default.join(dirName, migrationsTemplateFileName || defaultMigrationsTemplateFileName),
@@ -55,6 +71,10 @@ const buildKnexConfig = (dirName, appConfig) => {
55
71
  directory: path_1.default.join(dirName, seedsFolderProd || seedsFolder || defaultSeedsFolder),
56
72
  } }),
57
73
  };
58
- return (0, lodash_1.get)(config, nodeEnv);
74
+ let config2use = (0, lodash_1.get)(config, nodeEnv);
75
+ if (!config2use) {
76
+ config2use = config.development;
77
+ }
78
+ return config2use;
59
79
  };
60
80
  exports.buildKnexConfig = buildKnexConfig;
@@ -7,8 +7,10 @@ exports.verifyUserToken = exports.createUserToken = exports.getDefaultJwtIssuer
7
7
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
8
  const uuid_1 = require("uuid");
9
9
  const api_helpers_1 = require("@sdflc/api-helpers");
10
- let defaultJwtAlgorithm = 'HS256';
11
- let defaultIssuer = 'microservices-auth';
10
+ const constants_1 = require("./constants");
11
+ const dayjs_1 = __importDefault(require("dayjs"));
12
+ let defaultJwtAlgorithm = constants_1.DEFAULT_JWT_ALGORITHM;
13
+ let defaultIssuer = constants_1.DEFAULT_JWT_ISSUER;
12
14
  const setDefaultJwtAlgorithm = (algorithm) => {
13
15
  defaultJwtAlgorithm = algorithm;
14
16
  };
@@ -73,7 +75,10 @@ const verifyUserToken = (token, secret, args) => {
73
75
  }
74
76
  catch (ex) {
75
77
  if (ex.name === 'TokenExpiredError') {
76
- return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, 'User authorization has expired');
78
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `User authorization has expired at ${(0, dayjs_1.default)(ex.expiredAt).toDate()}`);
79
+ }
80
+ else if (ex.name === 'JsonWebTokenError') {
81
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `JWT is invalid, reason: ${ex.message}`);
77
82
  }
78
83
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED, null, 'User unauthenticated');
79
84
  }
package/build/utils.js CHANGED
@@ -1,14 +1,18 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.setFunctions = exports.setFunction = void 0;
7
+ const check_types_1 = __importDefault(require("check-types"));
4
8
  const setFunction = (func, defaultFunc) => {
5
- return typeof func === 'function' ? func : defaultFunc;
9
+ return check_types_1.default.function(func) ? func : defaultFunc;
6
10
  };
7
11
  exports.setFunction = setFunction;
8
12
  const setFunctions = (obj, defaultFuncs = {}) => {
9
13
  const keys = Object.keys(defaultFuncs || {});
10
14
  return keys.reduce((acc, key) => {
11
- if (typeof obj[key] === 'function') {
15
+ if (check_types_1.default.function(obj[key])) {
12
16
  acc[key] = obj[key];
13
17
  }
14
18
  return acc;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.63",
3
+ "version": "1.0.64",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",