@sdflc/backend-helpers 1.0.77 → 1.0.78

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 (106) hide show
  1. package/README.md +178 -178
  2. package/build/BaseCore.d.ts +88 -88
  3. package/build/BaseCore.js +819 -819
  4. package/build/BaseGateway.d.ts +49 -49
  5. package/build/BaseGateway.js +484 -484
  6. package/build/DataCache.d.ts +14 -14
  7. package/build/DataCache.js +104 -104
  8. package/build/Database.d.ts +32 -32
  9. package/build/Database.js +198 -198
  10. package/build/DbMigratorAndSeeder.d.ts +49 -49
  11. package/build/DbMigratorAndSeeder.js +238 -228
  12. package/build/RedisDataLoader.d.ts +41 -41
  13. package/build/RedisDataLoader.js +248 -248
  14. package/build/apiContext.d.ts +11 -11
  15. package/build/apiContext.js +143 -143
  16. package/build/{BaseController.d.ts → baseController.d.ts} +17 -17
  17. package/build/{BaseController.js → baseController.js} +66 -66
  18. package/build/checkItHelpers.d.ts +3 -3
  19. package/build/checkItHelpers.js +28 -28
  20. package/build/commonValidators.d.ts +17 -17
  21. package/build/commonValidators.js +298 -298
  22. package/build/configBulder.d.ts +2 -2
  23. package/build/configBulder.js +32 -32
  24. package/build/constants.d.ts +30 -30
  25. package/build/constants.js +80 -81
  26. package/build/dbHelpers.d.ts +43 -43
  27. package/build/dbHelpers.js +166 -166
  28. package/build/dbSeeder.d.ts +2 -2
  29. package/build/dbSeeder.js +92 -82
  30. package/build/dbTableHelpers.d.ts +11 -11
  31. package/build/dbTableHelpers.js +110 -110
  32. package/build/downloadHelpers.d.ts +2 -2
  33. package/build/downloadHelpers.js +83 -83
  34. package/build/index.d.ts +21 -21
  35. package/build/index.js +37 -37
  36. package/build/interfaces/ApiContext.d.ts +24 -24
  37. package/build/interfaces/ApiContext.js +2 -2
  38. package/build/interfaces/ApiContextInterface.d.ts +12 -12
  39. package/build/interfaces/ApiContextInterface.js +2 -2
  40. package/build/interfaces/BaseCoreActionsInterface.d.ts +38 -38
  41. package/build/interfaces/BaseCoreActionsInterface.js +2 -2
  42. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +12 -12
  43. package/build/interfaces/BaseCoreDoAuthOnActionInterface.js +2 -2
  44. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +13 -13
  45. package/build/interfaces/BaseCoreDoingWhatInterface.js +2 -2
  46. package/build/interfaces/BaseCorePropsInterface.d.ts +36 -36
  47. package/build/interfaces/BaseCorePropsInterface.js +2 -2
  48. package/build/interfaces/BaseCoreValidatorsInterface.d.ts +13 -13
  49. package/build/interfaces/BaseCoreValidatorsInterface.js +2 -2
  50. package/build/interfaces/BaseGatewayPropsInterface.d.ts +39 -39
  51. package/build/interfaces/BaseGatewayPropsInterface.js +2 -2
  52. package/build/interfaces/BuildConfigOptions.d.ts +6 -6
  53. package/build/interfaces/BuildConfigOptions.js +2 -2
  54. package/build/interfaces/BuildDefaultResolversOptions.d.ts +17 -17
  55. package/build/interfaces/BuildDefaultResolversOptions.js +2 -2
  56. package/build/interfaces/BuildListQueryArgsInterface.d.ts +6 -6
  57. package/build/interfaces/BuildListQueryArgsInterface.js +2 -2
  58. package/build/interfaces/CacheInterface.d.ts +15 -15
  59. package/build/interfaces/CacheInterface.js +2 -2
  60. package/build/interfaces/CommonValidatorArgs.d.ts +3 -3
  61. package/build/interfaces/CommonValidatorArgs.js +2 -2
  62. package/build/interfaces/CoreActionInterface.d.ts +14 -14
  63. package/build/interfaces/CoreActionInterface.js +2 -2
  64. package/build/interfaces/CreateUserTokenArgs.d.ts +11 -11
  65. package/build/interfaces/CreateUserTokenArgs.js +2 -2
  66. package/build/interfaces/CreateUserTokenResult.d.ts +4 -4
  67. package/build/interfaces/CreateUserTokenResult.js +2 -2
  68. package/build/interfaces/DatabaseOptions.d.ts +22 -22
  69. package/build/interfaces/DatabaseOptions.js +2 -2
  70. package/build/interfaces/DatabaseReadInterface.d.ts +14 -14
  71. package/build/interfaces/DatabaseReadInterface.js +2 -2
  72. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +9 -9
  73. package/build/interfaces/DbFieldAddDefaultInterface.js +2 -2
  74. package/build/interfaces/DownloadFileArgs.d.ts +6 -6
  75. package/build/interfaces/DownloadFileArgs.js +2 -2
  76. package/build/interfaces/ExtractCredentialsArgs.d.ts +19 -19
  77. package/build/interfaces/ExtractCredentialsArgs.js +2 -2
  78. package/build/interfaces/JwtTokenSecretAndSettings.d.ts +5 -5
  79. package/build/interfaces/JwtTokenSecretAndSettings.js +2 -2
  80. package/build/interfaces/ListArgsInterface.d.ts +5 -5
  81. package/build/interfaces/ListArgsInterface.js +2 -2
  82. package/build/interfaces/LoaderInterface.d.ts +4 -4
  83. package/build/interfaces/LoaderInterface.js +2 -2
  84. package/build/interfaces/PaginationInterface.d.ts +7 -7
  85. package/build/interfaces/PaginationInterface.js +2 -2
  86. package/build/interfaces/SortItemInterface.d.ts +4 -4
  87. package/build/interfaces/SortItemInterface.js +2 -2
  88. package/build/interfaces/UserTokenParams.d.ts +8 -8
  89. package/build/interfaces/UserTokenParams.js +2 -2
  90. package/build/interfaces/VerifyUserTokenArgs.d.ts +13 -13
  91. package/build/interfaces/VerifyUserTokenArgs.js +2 -2
  92. package/build/interfaces/index.d.ts +28 -28
  93. package/build/interfaces/index.js +43 -43
  94. package/build/knexConfigBuilder.d.ts +1 -1
  95. package/build/knexConfigBuilder.js +80 -80
  96. package/build/passwordHelpers.d.ts +5 -5
  97. package/build/passwordHelpers.js +30 -30
  98. package/build/redisClient.d.ts +17 -17
  99. package/build/redisClient.js +97 -97
  100. package/build/resolversHelpers.d.ts +3 -3
  101. package/build/resolversHelpers.js +62 -62
  102. package/build/userToken.d.ts +8 -8
  103. package/build/userToken.js +86 -86
  104. package/build/utils.d.ts +2 -2
  105. package/build/utils.js +21 -21
  106. package/package.json +71 -71
@@ -1,143 +1,143 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.createContextDefault = exports.createApiContext = void 0;
16
- const lodash_1 = require("lodash");
17
- const uuid_1 = require("uuid");
18
- const check_types_1 = __importDefault(require("check-types"));
19
- const utils_1 = require("@sdflc/utils");
20
- const Database_1 = require("./Database");
21
- const constants_1 = require("./constants");
22
- /**
23
- * Creates a GraphQL context object with all available cores.
24
- * @returns {object} A context object with all available cores
25
- */
26
- const createApiContext = (args) => __awaiter(void 0, void 0, void 0, function* () {
27
- const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
28
- const requestId = inRequestId || (0, uuid_1.v4)();
29
- const coreContext = check_types_1.default.function(getCoreContext) ? yield getCoreContext({ req }) : {};
30
- const gatewayContext = check_types_1.default.function(getGatewayContext) ? yield getGatewayContext({ req }) : {};
31
- const context = {
32
- requestId,
33
- cores: {},
34
- gateways: {},
35
- usedKeyPrefixes: {},
36
- req,
37
- res,
38
- };
39
- context.cores = Object.keys(cores || {}).reduce((acc, key) => {
40
- acc[(0, lodash_1.camelCase)(key)] = new cores[key](Object.assign(Object.assign({}, coreContext), { context }));
41
- return acc;
42
- }, {});
43
- context.gateways = Object.keys(gateways || {}).reduce((acc, key) => {
44
- acc[(0, lodash_1.camelCase)(key)] = new gateways[key](Object.assign(Object.assign({}, gatewayContext), { context }));
45
- return acc;
46
- }, {});
47
- if (check_types_1.default.function(extendContext)) {
48
- yield extendContext({ context, req });
49
- }
50
- return context;
51
- });
52
- exports.createApiContext = createApiContext;
53
- /**
54
- * Creates default a GraphQL context object with all avilable cores.
55
- * @returns {object} A context object with all available cores
56
- */
57
- const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, function* () {
58
- const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
59
- const headers = req.headers || { noHeadersSetup: true };
60
- const cookies = req.cookies || { noCookiesSetup: true };
61
- const authorization = (headers[constants_1.HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
62
- const fingerprint = headers[constants_1.HEADERS.FINGERPRINT] || '';
63
- const spaceId = headers[constants_1.HEADERS.SPACE_ID];
64
- const apiKey = headers[constants_1.HEADERS.API_KEY];
65
- const managementApiKey = headers[constants_1.HEADERS.MANAGEMENT_API_KEY];
66
- const userAgent = headers[constants_1.HEADERS.USER_AGENT];
67
- const referer = headers[constants_1.HEADERS.REFERER];
68
- const ipAddress = headers[constants_1.HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
69
- const acceptLanguage = headers[constants_1.HEADERS.ACCEPT_LANGUAGE];
70
- const languages = (0, utils_1.extractLanguages)(acceptLanguage);
71
- const requestedLang = headers[constants_1.HEADERS.REQUESTED_LANGUAGE] || (languages === null || languages === void 0 ? void 0 : languages[0]) || 'en';
72
- // const accountId = headers[HEADERS.ACCOUNT_ID];
73
- // const roleId = headers[HEADERS.ROLE_ID];
74
- // const userId = headers[HEADERS.USER_ID];
75
- const requestId = (0, uuid_1.v4)();
76
- const db = inDb
77
- ? inDb
78
- : new Database_1.Database({
79
- knexConfig,
80
- dbSchema,
81
- logger,
82
- });
83
- const sharedContext = {
84
- spaceId,
85
- apiKey,
86
- managementApiKey,
87
- userAgent,
88
- referer,
89
- ipAddress,
90
- acceptLanguage,
91
- languages,
92
- requestedLang,
93
- authorization,
94
- fingerprint,
95
- // accountId,
96
- // roleId,
97
- // userId,
98
- req,
99
- res,
100
- headers,
101
- cookies,
102
- authorizationToken,
103
- isExternalDb: !!inDb,
104
- };
105
- return yield (0, exports.createApiContext)({
106
- cores,
107
- gateways,
108
- req,
109
- res,
110
- requestId,
111
- extendContext: ({ context, req }) => __awaiter(void 0, void 0, void 0, function* () {
112
- context.db = db;
113
- Object.assign(context, sharedContext);
114
- if (check_types_1.default.function(extendContext)) {
115
- yield extendContext({ context, req });
116
- }
117
- }),
118
- getCoreContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
119
- // TODO: const { req } = args;
120
- let extendCoreConext = {};
121
- if (check_types_1.default.function(getCoreContext)) {
122
- extendCoreConext = yield getCoreContext(args);
123
- }
124
- return Object.assign({ db, gatewayName: '', isProduction,
125
- logger,
126
- doAuth,
127
- spaceGw,
128
- interserviceApiKey,
129
- jwtSecret,
130
- verifyTokenArgs }, (extendCoreConext || {}));
131
- }),
132
- getGatewayContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
133
- let extendGatewayConext = {};
134
- if (check_types_1.default.function(getGatewayContext)) {
135
- extendGatewayConext = yield getGatewayContext(args);
136
- }
137
- return Object.assign({ db,
138
- isProduction,
139
- logger }, (extendGatewayConext || {}));
140
- }),
141
- });
142
- });
143
- exports.createContextDefault = createContextDefault;
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createContextDefault = exports.createApiContext = void 0;
16
+ const lodash_1 = require("lodash");
17
+ const uuid_1 = require("uuid");
18
+ const check_types_1 = __importDefault(require("check-types"));
19
+ const utils_1 = require("@sdflc/utils");
20
+ const Database_1 = require("./Database");
21
+ const constants_1 = require("./constants");
22
+ /**
23
+ * Creates a GraphQL context object with all available cores.
24
+ * @returns {object} A context object with all available cores
25
+ */
26
+ const createApiContext = (args) => __awaiter(void 0, void 0, void 0, function* () {
27
+ const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
28
+ const requestId = inRequestId || (0, uuid_1.v4)();
29
+ const coreContext = check_types_1.default.function(getCoreContext) ? yield getCoreContext({ req }) : {};
30
+ const gatewayContext = check_types_1.default.function(getGatewayContext) ? yield getGatewayContext({ req }) : {};
31
+ const context = {
32
+ requestId,
33
+ cores: {},
34
+ gateways: {},
35
+ usedKeyPrefixes: {},
36
+ req,
37
+ res,
38
+ };
39
+ context.cores = Object.keys(cores || {}).reduce((acc, key) => {
40
+ acc[(0, lodash_1.camelCase)(key)] = new cores[key](Object.assign(Object.assign({}, coreContext), { context }));
41
+ return acc;
42
+ }, {});
43
+ context.gateways = Object.keys(gateways || {}).reduce((acc, key) => {
44
+ acc[(0, lodash_1.camelCase)(key)] = new gateways[key](Object.assign(Object.assign({}, gatewayContext), { context }));
45
+ return acc;
46
+ }, {});
47
+ if (check_types_1.default.function(extendContext)) {
48
+ yield extendContext({ context, req });
49
+ }
50
+ return context;
51
+ });
52
+ exports.createApiContext = createApiContext;
53
+ /**
54
+ * Creates default a GraphQL context object with all avilable cores.
55
+ * @returns {object} A context object with all available cores
56
+ */
57
+ const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, function* () {
58
+ const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
59
+ const headers = req.headers || { noHeadersSetup: true };
60
+ const cookies = req.cookies || { noCookiesSetup: true };
61
+ const authorization = (headers[constants_1.HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
62
+ const fingerprint = headers[constants_1.HEADERS.FINGERPRINT] || '';
63
+ const spaceId = headers[constants_1.HEADERS.SPACE_ID];
64
+ const apiKey = headers[constants_1.HEADERS.API_KEY];
65
+ const managementApiKey = headers[constants_1.HEADERS.MANAGEMENT_API_KEY];
66
+ const userAgent = headers[constants_1.HEADERS.USER_AGENT];
67
+ const referer = headers[constants_1.HEADERS.REFERER];
68
+ const ipAddress = headers[constants_1.HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
69
+ const acceptLanguage = headers[constants_1.HEADERS.ACCEPT_LANGUAGE];
70
+ const languages = (0, utils_1.extractLanguages)(acceptLanguage);
71
+ const requestedLang = headers[constants_1.HEADERS.REQUESTED_LANGUAGE] || (languages === null || languages === void 0 ? void 0 : languages[0]) || 'en';
72
+ // const accountId = headers[HEADERS.ACCOUNT_ID];
73
+ // const roleId = headers[HEADERS.ROLE_ID];
74
+ // const userId = headers[HEADERS.USER_ID];
75
+ const requestId = (0, uuid_1.v4)();
76
+ const db = inDb
77
+ ? inDb
78
+ : new Database_1.Database({
79
+ knexConfig,
80
+ dbSchema,
81
+ logger,
82
+ });
83
+ const sharedContext = {
84
+ spaceId,
85
+ apiKey,
86
+ managementApiKey,
87
+ userAgent,
88
+ referer,
89
+ ipAddress,
90
+ acceptLanguage,
91
+ languages,
92
+ requestedLang,
93
+ authorization,
94
+ fingerprint,
95
+ // accountId,
96
+ // roleId,
97
+ // userId,
98
+ req,
99
+ res,
100
+ headers,
101
+ cookies,
102
+ authorizationToken,
103
+ isExternalDb: !!inDb,
104
+ };
105
+ return yield (0, exports.createApiContext)({
106
+ cores,
107
+ gateways,
108
+ req,
109
+ res,
110
+ requestId,
111
+ extendContext: (_a) => __awaiter(void 0, [_a], void 0, function* ({ context, req }) {
112
+ context.db = db;
113
+ Object.assign(context, sharedContext);
114
+ if (check_types_1.default.function(extendContext)) {
115
+ yield extendContext({ context, req });
116
+ }
117
+ }),
118
+ getCoreContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
119
+ // TODO: const { req } = args;
120
+ let extendCoreConext = {};
121
+ if (check_types_1.default.function(getCoreContext)) {
122
+ extendCoreConext = yield getCoreContext(args);
123
+ }
124
+ return Object.assign({ db, gatewayName: '', isProduction,
125
+ logger,
126
+ doAuth,
127
+ spaceGw,
128
+ interserviceApiKey,
129
+ jwtSecret,
130
+ verifyTokenArgs }, (extendCoreConext || {}));
131
+ }),
132
+ getGatewayContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
133
+ let extendGatewayConext = {};
134
+ if (check_types_1.default.function(getGatewayContext)) {
135
+ extendGatewayConext = yield getGatewayContext(args);
136
+ }
137
+ return Object.assign({ db,
138
+ isProduction,
139
+ logger }, (extendGatewayConext || {}));
140
+ }),
141
+ });
142
+ });
143
+ exports.createContextDefault = createContextDefault;
@@ -1,17 +1,17 @@
1
- import { Logger } from '@sdflc/utils';
2
- /**
3
- * Base class for REST API controllers.
4
- */
5
- declare class BaseController {
6
- protected onResponse: any;
7
- protected logger: Logger;
8
- constructor(props: any);
9
- init(props: any): void;
10
- /**
11
- * Executes an action method and returns result in consistent way.
12
- * @param method a function to be executed
13
- * @returns HTTP response
14
- */
15
- json(method: any): (req: any, res: any, next: any) => Promise<void>;
16
- }
17
- export { BaseController };
1
+ import { Logger } from '@sdflc/utils';
2
+ /**
3
+ * Base class for REST API controllers.
4
+ */
5
+ declare class BaseController {
6
+ protected onResponse: any;
7
+ protected logger: Logger;
8
+ constructor(props: any);
9
+ init(props: any): void;
10
+ /**
11
+ * Executes an action method and returns result in consistent way.
12
+ * @param method a function to be executed
13
+ * @returns HTTP response
14
+ */
15
+ json(method: any): (req: any, res: any, next: any) => Promise<void>;
16
+ }
17
+ export { BaseController };
@@ -1,66 +1,66 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.BaseController = void 0;
16
- const check_types_1 = __importDefault(require("check-types"));
17
- const api_helpers_1 = require("@sdflc/api-helpers");
18
- const utils_1 = require("@sdflc/utils");
19
- /**
20
- * Base class for REST API controllers.
21
- */
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 === null || props === void 0 ? void 0 : props.logger) instanceof utils_1.Logger ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
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
- }
39
- /**
40
- * Executes an action method and returns result in consistent way.
41
- * @param method a function to be executed
42
- * @returns HTTP response
43
- */
44
- json(method) {
45
- return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
46
- try {
47
- const result = yield method(req, res, next);
48
- if (result instanceof api_helpers_1.OpResult) {
49
- res.status(result.getHttpStatus()).json(result.toJS());
50
- }
51
- else if (result) {
52
- res.status(200).json(result);
53
- }
54
- else {
55
- res.status(204).json(new api_helpers_1.OpResult());
56
- }
57
- yield this.onResponse(req, res, next);
58
- }
59
- catch (ex) {
60
- this.logger.log(`An exception has occured when processing REST API request on the entry point '${req.method} ${req.originalUrl}' from ${req.ip}`);
61
- next(ex);
62
- }
63
- });
64
- }
65
- }
66
- exports.BaseController = BaseController;
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.BaseController = void 0;
16
+ const check_types_1 = __importDefault(require("check-types"));
17
+ const api_helpers_1 = require("@sdflc/api-helpers");
18
+ const utils_1 = require("@sdflc/utils");
19
+ /**
20
+ * Base class for REST API controllers.
21
+ */
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 === null || props === void 0 ? void 0 : props.logger) instanceof utils_1.Logger ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
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
+ }
39
+ /**
40
+ * Executes an action method and returns result in consistent way.
41
+ * @param method a function to be executed
42
+ * @returns HTTP response
43
+ */
44
+ json(method) {
45
+ return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
46
+ try {
47
+ const result = yield method(req, res, next);
48
+ if (result instanceof api_helpers_1.OpResult) {
49
+ res.status(result.getHttpStatus()).json(result.toJS());
50
+ }
51
+ else if (result) {
52
+ res.status(200).json(result);
53
+ }
54
+ else {
55
+ res.status(204).json(new api_helpers_1.OpResult());
56
+ }
57
+ yield this.onResponse(req, res, next);
58
+ }
59
+ catch (ex) {
60
+ this.logger.log(`An exception has occured when processing REST API request on the entry point '${req.method} ${req.originalUrl}' from ${req.ip}`);
61
+ next(ex);
62
+ }
63
+ });
64
+ }
65
+ }
66
+ exports.BaseController = BaseController;
@@ -1,3 +1,3 @@
1
- import { OpResult } from '@sdflc/api-helpers';
2
- export declare const checkArray: (arr: any, validator: any, prefix?: string) => OpResult;
3
- export declare const createErrorOnCheckError: (checkItResult: any) => OpResult;
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ export declare const checkArray: (arr: any, validator: any, prefix?: string) => OpResult;
3
+ export declare const createErrorOnCheckError: (checkItResult: any) => OpResult;
@@ -1,28 +1,28 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createErrorOnCheckError = exports.checkArray = void 0;
4
- const api_helpers_1 = require("@sdflc/api-helpers");
5
- const checkArray = (arr, validator, prefix) => {
6
- const result = new api_helpers_1.OpResult();
7
- if (!Array.isArray(arr)) {
8
- return result.addError(prefix || '', 'The value should be an array');
9
- }
10
- arr.forEach((item, idx) => {
11
- const [itemResult] = validator.validateSync(item);
12
- if (itemResult) {
13
- Object.keys(itemResult.errors).forEach((key) => {
14
- result.addError(`${prefix || ''}[${idx}].${key}`, itemResult.errors[key].message);
15
- });
16
- }
17
- });
18
- return result;
19
- };
20
- exports.checkArray = checkArray;
21
- const createErrorOnCheckError = (checkItResult) => {
22
- const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
23
- Object.keys(checkItResult.errors).forEach((key) => {
24
- result.addError(key, checkItResult.errors[key].message);
25
- });
26
- return result;
27
- };
28
- exports.createErrorOnCheckError = createErrorOnCheckError;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createErrorOnCheckError = exports.checkArray = void 0;
4
+ const api_helpers_1 = require("@sdflc/api-helpers");
5
+ const checkArray = (arr, validator, prefix) => {
6
+ const result = new api_helpers_1.OpResult();
7
+ if (!Array.isArray(arr)) {
8
+ return result.addError(prefix || '', 'The value should be an array');
9
+ }
10
+ arr.forEach((item, idx) => {
11
+ const [itemResult] = validator.validateSync(item);
12
+ if (itemResult) {
13
+ Object.keys(itemResult.errors).forEach((key) => {
14
+ result.addError(`${prefix || ''}[${idx}].${key}`, itemResult.errors[key].message);
15
+ });
16
+ }
17
+ });
18
+ return result;
19
+ };
20
+ exports.checkArray = checkArray;
21
+ const createErrorOnCheckError = (checkItResult) => {
22
+ const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
23
+ Object.keys(checkItResult.errors).forEach((key) => {
24
+ result.addError(key, checkItResult.errors[key].message);
25
+ });
26
+ return result;
27
+ };
28
+ exports.createErrorOnCheckError = createErrorOnCheckError;
@@ -1,17 +1,17 @@
1
- import { OpResult } from '@sdflc/api-helpers';
2
- import { BaseCoreActionsInterface, CommonValidatorArgs } from './interfaces';
3
- export declare const shouldHaveParams: (args: any) => boolean[] | OpResult[];
4
- export declare const shouldHaveId: (id: any) => boolean[] | OpResult[];
5
- export declare const validateSingleIntId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
6
- export declare const validateSingleUuidId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
7
- export declare const validateSingleTextId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
8
- export declare const validateMultipleIntIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
9
- export declare const validateMultipleUuidIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
10
- export declare const validateMultipleTextIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
11
- export declare const validateList: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
12
- export declare const validateGet: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
13
- export declare const validateRemove: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
14
- export declare const validateGetMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
15
- export declare const validateRemoveMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
16
- export declare const validateCreate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
17
- export declare const validateUpdate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseCoreActionsInterface, CommonValidatorArgs } from './interfaces';
3
+ export declare const shouldHaveParams: (args: any) => boolean[] | OpResult[];
4
+ export declare const shouldHaveId: (id: any) => boolean[] | OpResult[];
5
+ export declare const validateSingleIntId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
6
+ export declare const validateSingleUuidId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
7
+ export declare const validateSingleTextId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
8
+ export declare const validateMultipleIntIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
9
+ export declare const validateMultipleUuidIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
10
+ export declare const validateMultipleTextIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
11
+ export declare const validateList: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
12
+ export declare const validateGet: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
13
+ export declare const validateRemove: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
14
+ export declare const validateGetMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
15
+ export declare const validateRemoveMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
16
+ export declare const validateCreate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
17
+ export declare const validateUpdate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;