@sdflc/backend-helpers 1.0.78 → 1.0.80

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 (123) hide show
  1. package/build/BaseCore.js +496 -603
  2. package/build/BaseGateway.js +331 -379
  3. package/build/DataCache.js +16 -19
  4. package/build/Database.js +55 -74
  5. package/build/DbMigratorAndSeeder.js +88 -114
  6. package/build/RedisDataLoader.js +153 -189
  7. package/build/apiContext.js +35 -33
  8. package/build/baseController.js +9 -16
  9. package/build/commonValidators.js +22 -37
  10. package/build/configBulder.js +5 -1
  11. package/build/dbHelpers.js +19 -29
  12. package/build/dbSeeder.js +11 -20
  13. package/build/dbTableHelpers.js +10 -10
  14. package/build/downloadHelpers.js +15 -25
  15. package/build/esm/BaseCore.d.ts +88 -0
  16. package/build/esm/BaseCore.js +706 -0
  17. package/build/esm/BaseGateway.d.ts +49 -0
  18. package/build/esm/BaseGateway.js +430 -0
  19. package/build/esm/DataCache.d.ts +14 -0
  20. package/build/esm/DataCache.js +95 -0
  21. package/build/esm/Database.d.ts +32 -0
  22. package/build/esm/Database.js +173 -0
  23. package/build/esm/DbMigratorAndSeeder.d.ts +49 -0
  24. package/build/esm/DbMigratorAndSeeder.js +173 -0
  25. package/build/esm/RedisDataLoader.d.ts +41 -0
  26. package/build/esm/RedisDataLoader.js +206 -0
  27. package/build/esm/apiContext.d.ts +11 -0
  28. package/build/esm/apiContext.js +137 -0
  29. package/build/esm/baseController.d.ts +17 -0
  30. package/build/esm/baseController.js +53 -0
  31. package/build/esm/checkItHelpers.d.ts +3 -0
  32. package/build/esm/checkItHelpers.js +23 -0
  33. package/build/esm/commonValidators.d.ts +17 -0
  34. package/build/esm/commonValidators.js +264 -0
  35. package/build/esm/configBulder.d.ts +2 -0
  36. package/build/esm/configBulder.js +32 -0
  37. package/build/esm/constants.d.ts +30 -0
  38. package/build/esm/constants.js +69 -0
  39. package/build/esm/dbHelpers.d.ts +43 -0
  40. package/build/esm/dbHelpers.js +144 -0
  41. package/build/esm/dbSeeder.d.ts +2 -0
  42. package/build/esm/dbSeeder.js +44 -0
  43. package/build/esm/dbTableHelpers.d.ts +11 -0
  44. package/build/esm/dbTableHelpers.js +99 -0
  45. package/build/esm/downloadHelpers.d.ts +2 -0
  46. package/build/esm/downloadHelpers.js +66 -0
  47. package/build/esm/index.d.ts +21 -0
  48. package/build/esm/index.js +21 -0
  49. package/build/esm/interfaces/ApiContext.d.ts +24 -0
  50. package/build/esm/interfaces/ApiContext.js +1 -0
  51. package/build/esm/interfaces/ApiContextInterface.d.ts +12 -0
  52. package/build/esm/interfaces/ApiContextInterface.js +1 -0
  53. package/build/esm/interfaces/BaseCoreActionsInterface.d.ts +38 -0
  54. package/build/esm/interfaces/BaseCoreActionsInterface.js +1 -0
  55. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +12 -0
  56. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.js +1 -0
  57. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +13 -0
  58. package/build/esm/interfaces/BaseCoreDoingWhatInterface.js +1 -0
  59. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +36 -0
  60. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  61. package/build/esm/interfaces/BaseCoreValidatorsInterface.d.ts +13 -0
  62. package/build/esm/interfaces/BaseCoreValidatorsInterface.js +1 -0
  63. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +39 -0
  64. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  65. package/build/esm/interfaces/BuildConfigOptions.d.ts +6 -0
  66. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  67. package/build/esm/interfaces/BuildDefaultResolversOptions.d.ts +17 -0
  68. package/build/esm/interfaces/BuildDefaultResolversOptions.js +1 -0
  69. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +6 -0
  70. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  71. package/build/esm/interfaces/CacheInterface.d.ts +15 -0
  72. package/build/esm/interfaces/CacheInterface.js +1 -0
  73. package/build/esm/interfaces/CommonValidatorArgs.d.ts +3 -0
  74. package/build/esm/interfaces/CommonValidatorArgs.js +1 -0
  75. package/build/esm/interfaces/CoreActionInterface.d.ts +14 -0
  76. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  77. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +11 -0
  78. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  79. package/build/esm/interfaces/CreateUserTokenResult.d.ts +4 -0
  80. package/build/esm/interfaces/CreateUserTokenResult.js +1 -0
  81. package/build/esm/interfaces/DatabaseOptions.d.ts +22 -0
  82. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  83. package/build/esm/interfaces/DatabaseReadInterface.d.ts +14 -0
  84. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  85. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +9 -0
  86. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  87. package/build/esm/interfaces/DownloadFileArgs.d.ts +6 -0
  88. package/build/esm/interfaces/DownloadFileArgs.js +1 -0
  89. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +19 -0
  90. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  91. package/build/esm/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
  92. package/build/esm/interfaces/JwtTokenSecretAndSettings.js +1 -0
  93. package/build/esm/interfaces/ListArgsInterface.d.ts +5 -0
  94. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  95. package/build/esm/interfaces/LoaderInterface.d.ts +4 -0
  96. package/build/esm/interfaces/LoaderInterface.js +1 -0
  97. package/build/esm/interfaces/PaginationInterface.d.ts +7 -0
  98. package/build/esm/interfaces/PaginationInterface.js +1 -0
  99. package/build/esm/interfaces/SortItemInterface.d.ts +4 -0
  100. package/build/esm/interfaces/SortItemInterface.js +1 -0
  101. package/build/esm/interfaces/UserTokenParams.d.ts +8 -0
  102. package/build/esm/interfaces/UserTokenParams.js +1 -0
  103. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +13 -0
  104. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  105. package/build/esm/interfaces/index.d.ts +28 -0
  106. package/build/esm/interfaces/index.js +27 -0
  107. package/build/esm/knexConfigBuilder.d.ts +1 -0
  108. package/build/esm/knexConfigBuilder.js +83 -0
  109. package/build/esm/passwordHelpers.d.ts +5 -0
  110. package/build/esm/passwordHelpers.js +13 -0
  111. package/build/esm/redisClient.d.ts +17 -0
  112. package/build/esm/redisClient.js +94 -0
  113. package/build/esm/resolversHelpers.d.ts +3 -0
  114. package/build/esm/resolversHelpers.js +66 -0
  115. package/build/esm/userToken.d.ts +8 -0
  116. package/build/esm/userToken.js +74 -0
  117. package/build/esm/utils.d.ts +2 -0
  118. package/build/esm/utils.js +13 -0
  119. package/build/knexConfigBuilder.js +17 -7
  120. package/build/passwordHelpers.js +7 -16
  121. package/build/resolversHelpers.js +11 -4
  122. package/build/userToken.js +2 -2
  123. package/package.json +13 -6
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -153,66 +144,64 @@ const shouldHaveId = (id) => {
153
144
  return [true];
154
145
  };
155
146
  exports.shouldHaveId = shouldHaveId;
156
- const validateSingleIntId = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
147
+ const validateSingleIntId = async (args, opt) => {
157
148
  const [result] = rulesSingleIntId.validateSync(args);
158
149
  if (result) {
159
150
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
160
151
  }
161
152
  return [true, {}];
162
- });
153
+ };
163
154
  exports.validateSingleIntId = validateSingleIntId;
164
- const validateSingleUuidId = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
155
+ const validateSingleUuidId = async (args, opt) => {
165
156
  const [result] = rulesSingleUuidId.validateSync(args);
166
157
  if (result) {
167
158
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
168
159
  }
169
160
  return [true, {}];
170
- });
161
+ };
171
162
  exports.validateSingleUuidId = validateSingleUuidId;
172
- const validateSingleTextId = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
163
+ const validateSingleTextId = async (args, opt) => {
173
164
  const [result] = rulesSingleTextId.validateSync(args);
174
165
  if (result) {
175
166
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
176
167
  }
177
168
  return [true, {}];
178
- });
169
+ };
179
170
  exports.validateSingleTextId = validateSingleTextId;
180
- const validateMultipleIntIds = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
171
+ const validateMultipleIntIds = async (args, opt) => {
181
172
  const [result] = rulesMultipleIntIds.validateSync(args);
182
173
  if (result) {
183
174
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
184
175
  }
185
176
  return [true, {}];
186
- });
177
+ };
187
178
  exports.validateMultipleIntIds = validateMultipleIntIds;
188
- const validateMultipleUuidIds = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
179
+ const validateMultipleUuidIds = async (args, opt) => {
189
180
  const [result] = rulesMultipleUuidIds.validateSync(args);
190
181
  if (result) {
191
182
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
192
183
  }
193
184
  return [true, {}];
194
- });
185
+ };
195
186
  exports.validateMultipleUuidIds = validateMultipleUuidIds;
196
- const validateMultipleTextIds = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
187
+ const validateMultipleTextIds = async (args, opt) => {
197
188
  const [result] = rulesMultipleTextIds.validateSync(args);
198
189
  if (result) {
199
190
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
200
191
  }
201
192
  return [true, {}];
202
- });
193
+ };
203
194
  exports.validateMultipleTextIds = validateMultipleTextIds;
204
- const validateList = ({ rules }) =>
205
- // eslint-disable-next-line
206
- (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
195
+ const validateList = ({ rules }) => async (args, opt) => {
207
196
  const { filter } = args || {};
208
197
  const [result] = rules.validateSync(filter);
209
198
  if (result) {
210
199
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
211
200
  }
212
201
  return [true, {}];
213
- });
202
+ };
214
203
  exports.validateList = validateList;
215
- const validateGet = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
204
+ const validateGet = async (args, opt) => {
216
205
  const idType = opt.core.getIdType();
217
206
  let rules = null;
218
207
  switch (idType) {
@@ -234,10 +223,10 @@ const validateGet = (args, opt) => __awaiter(void 0, void 0, void 0, function* (
234
223
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
235
224
  }
236
225
  return [true, {}];
237
- });
226
+ };
238
227
  exports.validateGet = validateGet;
239
228
  exports.validateRemove = exports.validateGet;
240
- const validateGetMany = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
229
+ const validateGetMany = async (args, opt) => {
241
230
  const idType = opt.core.getIdType();
242
231
  let rules = null;
243
232
  switch (idType) {
@@ -259,12 +248,10 @@ const validateGetMany = (args, opt) => __awaiter(void 0, void 0, void 0, functio
259
248
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
260
249
  }
261
250
  return [true, {}];
262
- });
251
+ };
263
252
  exports.validateGetMany = validateGetMany;
264
253
  exports.validateRemoveMany = exports.validateGetMany;
265
- const validateCreate = ({ rules }) =>
266
- // eslint-disable-next-line
267
- (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
254
+ const validateCreate = ({ rules }) => async (args, opt) => {
268
255
  const { params } = args || {};
269
256
  const [paramsCheck] = (0, exports.shouldHaveParams)(params);
270
257
  if (paramsCheck !== true) {
@@ -275,11 +262,9 @@ const validateCreate = ({ rules }) =>
275
262
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result), {}];
276
263
  }
277
264
  return [true, {}];
278
- });
265
+ };
279
266
  exports.validateCreate = validateCreate;
280
- const validateUpdate = ({ rules }) =>
281
- // eslint-disable-next-line
282
- (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
267
+ const validateUpdate = ({ rules }) => async (args, opt) => {
283
268
  const { where, params } = args || {};
284
269
  const [idCheck] = (0, exports.shouldHaveParams)(where);
285
270
  if (idCheck !== true) {
@@ -294,5 +279,5 @@ const validateUpdate = ({ rules }) =>
294
279
  return [(0, checkItHelpers_1.createErrorOnCheckError)(result), {}];
295
280
  }
296
281
  return [true, {}];
297
- });
282
+ };
298
283
  exports.validateUpdate = validateUpdate;
@@ -27,6 +27,10 @@ const buildConfig = (dirName, opt) => {
27
27
  acc[(0, lodash_1.camelCase)(key)] = value;
28
28
  return acc;
29
29
  }, {});
30
- return Object.assign(Object.assign({}, envVars), { nodeEnv: env.NODE_ENV, isProduction: env.NODE_ENV === 'production' });
30
+ return {
31
+ ...envVars,
32
+ nodeEnv: env.NODE_ENV,
33
+ isProduction: env.NODE_ENV === 'production',
34
+ };
31
35
  };
32
36
  exports.buildConfig = buildConfig;
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -20,16 +11,16 @@ const SQLS = {
20
11
  listTablesSchema: (appSettings) => `
21
12
  SELECT TABLE_NAME as table_name
22
13
  FROM INFORMATION_SCHEMA.TABLES
23
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
14
+ WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
24
15
  `,
25
16
  listTables: () => `
26
17
  SELECT TABLE_NAME as table_name
27
18
  FROM INFORMATION_SCHEMA.TABLES
28
19
  `,
29
20
  dropTablesSchema: (appSettings) => `
30
- SELECT 'DROP TABLE IF EXISTS ${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}.' || TABLE_NAME || ';' as cmd
21
+ SELECT 'DROP TABLE IF EXISTS ${appSettings?.dbSchema}.' || TABLE_NAME || ';' as cmd
31
22
  FROM INFORMATION_SCHEMA.TABLES
32
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
23
+ WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
33
24
  `,
34
25
  dropTables: () => `
35
26
  SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd
@@ -40,16 +31,16 @@ const SQLS = {
40
31
  listTablesSchema: (appSettings) => `
41
32
  SELECT TABLE_NAME as table_name
42
33
  FROM INFORMATION_SCHEMA.TABLES
43
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
34
+ WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
44
35
  `,
45
36
  listTables: () => `
46
37
  SELECT TABLE_NAME as table_name
47
38
  FROM INFORMATION_SCHEMA.TABLES
48
39
  `,
49
40
  dropTablesSchema: (appSettings) => `
50
- SELECT 'DROP TABLE IF EXISTS [${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}].[' + TABLE_NAME + '];' as cmd
41
+ SELECT 'DROP TABLE IF EXISTS [${appSettings?.dbSchema}].[' + TABLE_NAME + '];' as cmd
51
42
  FROM INFORMATION_SCHEMA.TABLES
52
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
43
+ WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
53
44
  `,
54
45
  dropTables: () => `
55
46
  SELECT 'DROP TABLE IF EXISTS ' + TABLE_NAME + ';' as cmd
@@ -65,10 +56,9 @@ const SQLS = {
65
56
  * @param knexHandle Knex handle object with configured connection to DB
66
57
  * @param appSettings settings with db related information
67
58
  */
68
- const dbCleanTable = (table, knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
69
- var _a;
59
+ const dbCleanTable = async (table, knexHandle, appSettings) => {
70
60
  const query = knexHandle(table).withSchema(appSettings.dbSchema).delete();
71
- const cleanTableFilters = (_a = appSettings === null || appSettings === void 0 ? void 0 : appSettings.cleanTableFilters) === null || _a === void 0 ? void 0 : _a[table];
61
+ const cleanTableFilters = appSettings?.cleanTableFilters?.[table];
72
62
  if (cleanTableFilters != undefined) {
73
63
  if (Array.isArray(cleanTableFilters.where)) {
74
64
  cleanTableFilters.where.forEach((whereItem) => {
@@ -76,8 +66,8 @@ const dbCleanTable = (table, knexHandle, appSettings) => __awaiter(void 0, void
76
66
  });
77
67
  }
78
68
  }
79
- yield query;
80
- });
69
+ await query;
70
+ };
81
71
  exports.dbCleanTable = dbCleanTable;
82
72
  /**
83
73
  * Returns a list of tables in db schedm specified in settings
@@ -85,17 +75,17 @@ exports.dbCleanTable = dbCleanTable;
85
75
  * @param appSettings settings with db related information
86
76
  * @returns arrays of table names in the provided db schema
87
77
  */
88
- const dbListTables = (knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
78
+ const dbListTables = async (knexHandle, appSettings) => {
89
79
  const skipTables = (appSettings || {}).skipTables || [];
90
80
  let query = SQLS[appSettings.dbType].listTablesSchema(appSettings);
91
81
  if (!appSettings.dbSchema) {
92
82
  query = SQLS[appSettings.dbType].listTables(appSettings);
93
83
  }
94
- const tables = yield knexHandle.raw(query);
84
+ const tables = await knexHandle.raw(query);
95
85
  return (tables.rows || [])
96
86
  .map((row) => row.table_name)
97
87
  .filter((table) => skipTables.indexOf(table) === -1);
98
- });
88
+ };
99
89
  exports.dbListTables = dbListTables;
100
90
  /**
101
91
  * Removes all the records from provided list of tables
@@ -104,14 +94,14 @@ exports.dbListTables = dbListTables;
104
94
  * @param appSettings settings with db related information
105
95
  * @returns promise
106
96
  */
107
- const dbClean = (tablesToClean, knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
97
+ const dbClean = async (tablesToClean, knexHandle, appSettings) => {
108
98
  for (let idx = 0, len = tablesToClean.length; idx < len; ++idx) {
109
- yield dbCleanTable(tablesToClean[idx], knexHandle, appSettings);
99
+ await dbCleanTable(tablesToClean[idx], knexHandle, appSettings);
110
100
  }
111
101
  return new bluebird_1.default((resolve) => {
112
102
  resolve(tablesToClean);
113
103
  });
114
- });
104
+ };
115
105
  exports.dbClean = dbClean;
116
106
  /**
117
107
  * Selects all the tables in the schema and drops them.
@@ -154,13 +144,13 @@ exports.dbTransformSeedsToObject = dbTransformSeedsToObject;
154
144
  const dbRunMigrations = (knexHandle, appSettings) => {
155
145
  return knexHandle.migrate
156
146
  .latest()
157
- .then((result) => __awaiter(void 0, void 0, void 0, function* () {
147
+ .then(async (result) => {
158
148
  if (appSettings && appSettings.runDbSeed && result[1].length > 0) {
159
- yield knexHandle.seed.run();
149
+ await knexHandle.seed.run();
160
150
  }
161
151
  console.log('Ran', result[1].length, 'migration(s)');
162
152
  return knexHandle.migrate.currentVersion();
163
- }))
153
+ })
164
154
  .then((version) => console.log('Current version of database: ', version));
165
155
  };
166
156
  exports.dbRunMigrations = dbRunMigrations;
package/build/dbSeeder.js CHANGED
@@ -32,15 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
- return new (P || (P = Promise))(function (resolve, reject) {
38
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
- step((generator = generator.apply(thisArg, _arguments || [])).next());
42
- });
43
- };
44
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
45
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
46
37
  };
@@ -49,10 +40,10 @@ exports.dbSeed = void 0;
49
40
  const path_1 = __importDefault(require("path"));
50
41
  const lodash_1 = require("lodash");
51
42
  const dbHelpers_1 = require("./dbHelpers");
52
- const generateSeeds = (dirname, seedFiles) => __awaiter(void 0, void 0, void 0, function* () {
43
+ const generateSeeds = async (dirname, seedFiles) => {
53
44
  let seedGroups = [];
54
45
  const seedFileNames = (0, lodash_1.flatten)(seedFiles);
55
- const seedFnExports = yield Promise.all((0, lodash_1.map)(seedFileNames, (filename) => Promise.resolve(`${path_1.default.join(dirname, `./objects/${filename}.js`)}`).then(s => __importStar(require(s)))));
46
+ const seedFnExports = await Promise.all((0, lodash_1.map)(seedFileNames, (filename) => Promise.resolve(`${path_1.default.join(dirname, `./objects/${filename}.js`)}`).then(s => __importStar(require(s)))));
56
47
  const seedFns = (0, lodash_1.map)(seedFnExports, 'default');
57
48
  const seedFnsMap = {};
58
49
  for (let i = 0; i < seedFileNames.length; i++) {
@@ -70,7 +61,7 @@ const generateSeeds = (dirname, seedFiles) => __awaiter(void 0, void 0, void 0,
70
61
  return seeds;
71
62
  }, {});
72
63
  return seedGroups;
73
- });
64
+ };
74
65
  const removeSeedsFromDb = (seedFiles, knexHandle, config) => {
75
66
  const tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
76
67
  console.log('Deleting records from tables: ', tablesToReset);
@@ -79,14 +70,14 @@ const removeSeedsFromDb = (seedFiles, knexHandle, config) => {
79
70
  const insertRecords = (seedGroups, knexHandle, config) => {
80
71
  const { dbSchema } = config || {};
81
72
  console.log('Inserting seeds records tables tables...');
82
- return seedGroups.reduce((previousGroup, group) => __awaiter(void 0, void 0, void 0, function* () {
83
- yield previousGroup;
73
+ return seedGroups.reduce(async (previousGroup, group) => {
74
+ await previousGroup;
84
75
  return Promise.all(Object.keys(group).map((table) => knexHandle(table).withSchema(dbSchema).insert(group[table])));
85
- }), Promise.resolve());
76
+ }, Promise.resolve());
77
+ };
78
+ const dbSeed = async (dirname, seedFiles, knexHandle, config) => {
79
+ const groups = await generateSeeds(dirname, seedFiles);
80
+ await removeSeedsFromDb(seedFiles, knexHandle, config);
81
+ return await insertRecords(groups, knexHandle, config);
86
82
  };
87
- const dbSeed = (dirname, seedFiles, knexHandle, config) => __awaiter(void 0, void 0, void 0, function* () {
88
- const groups = yield generateSeeds(dirname, seedFiles);
89
- yield removeSeedsFromDb(seedFiles, knexHandle, config);
90
- return yield insertRecords(groups, knexHandle, config);
91
- });
92
83
  exports.dbSeed = dbSeed;
@@ -9,14 +9,14 @@ const dbFieldAddDefaults = (table, opt) => {
9
9
  table
10
10
  .integer(constants_1.FIELDS.STATUS)
11
11
  .defaultTo(utils_1.STATUSES.ACTIVE)
12
- .comment((opt === null || opt === void 0 ? void 0 : opt.statusComment) ||
12
+ .comment(opt?.statusComment ||
13
13
  'The field is used to specify record status: 50 - Test, 100 - Active, 200 - Draft, 300 - Pending, 1000 - Blocked, 5000 - Disabled, 10000 - Removed');
14
14
  }
15
15
  if (addVersion) {
16
16
  table
17
17
  .integer(constants_1.FIELDS.VERSION)
18
18
  .defaultTo(0)
19
- .comment((opt === null || opt === void 0 ? void 0 : opt.versionComment) || 'The field is used to control versioning');
19
+ .comment(opt?.versionComment || 'The field is used to control versioning');
20
20
  }
21
21
  if (addUserInfo) {
22
22
  table.uuid(constants_1.FIELDS.CREATED_BY).comment('ID of user who created the record');
@@ -44,7 +44,7 @@ const dbFieldAddDefaults = (table, opt) => {
44
44
  exports.dbFieldAddDefaults = dbFieldAddDefaults;
45
45
  const addOrderNo = (table, opt) => {
46
46
  const chain = table.text(constants_1.FIELDS.ORDER_NO).notNullable().defaultTo('10000000');
47
- if ((opt === null || opt === void 0 ? void 0 : opt.addIndex) === true) {
47
+ if (opt?.addIndex === true) {
48
48
  table.index([constants_1.FIELDS.ORDER_NO]);
49
49
  }
50
50
  return chain;
@@ -56,7 +56,7 @@ const addAmount = (table, fieldName) => {
56
56
  exports.addAmount = addAmount;
57
57
  const addSpaceId = (table, opt) => {
58
58
  const chain = table.text(constants_1.FIELDS.SPACE_ID).notNullable().comment('Reference to the space table');
59
- if ((opt === null || opt === void 0 ? void 0 : opt.addForeignKey) === true) {
59
+ if (opt?.addForeignKey === true) {
60
60
  table.foreign(constants_1.FIELDS.SPACE_ID).references(`space.${constants_1.FIELDS.ID}`).onUpdate('CASCADE').onDelete('CASCADE');
61
61
  }
62
62
  return chain;
@@ -64,10 +64,10 @@ const addSpaceId = (table, opt) => {
64
64
  exports.addSpaceId = addSpaceId;
65
65
  const addUserId = (table, opt) => {
66
66
  const chain = table.uuid(constants_1.FIELDS.USER_ID).notNullable().comment('Reference to the user table');
67
- if ((opt === null || opt === void 0 ? void 0 : opt.addForeignKey) === true) {
67
+ if (opt?.addForeignKey === true) {
68
68
  table.foreign(constants_1.FIELDS.USER_ID).references(`user.${constants_1.FIELDS.ID}`).onUpdate('CASCADE').onDelete('CASCADE');
69
69
  }
70
- if ((opt === null || opt === void 0 ? void 0 : opt.addIndex) === true) {
70
+ if (opt?.addIndex === true) {
71
71
  table.index([constants_1.FIELDS.USER_ID]);
72
72
  }
73
73
  return chain;
@@ -75,10 +75,10 @@ const addUserId = (table, opt) => {
75
75
  exports.addUserId = addUserId;
76
76
  const addAccountId = (table, opt) => {
77
77
  const chain = table.uuid(constants_1.FIELDS.ACCOUNT_ID).notNullable().comment('Reference to the user table');
78
- if ((opt === null || opt === void 0 ? void 0 : opt.addForeignKey) === true) {
78
+ if (opt?.addForeignKey === true) {
79
79
  table.foreign(constants_1.FIELDS.ACCOUNT_ID).references(`account.${constants_1.FIELDS.ID}`).onUpdate('CASCADE').onDelete('CASCADE');
80
80
  }
81
- if ((opt === null || opt === void 0 ? void 0 : opt.addIndex) === true) {
81
+ if (opt?.addIndex === true) {
82
82
  table.index([constants_1.FIELDS.ACCOUNT_ID]);
83
83
  }
84
84
  return chain;
@@ -86,10 +86,10 @@ const addAccountId = (table, opt) => {
86
86
  exports.addAccountId = addAccountId;
87
87
  const addLang = (table, opt) => {
88
88
  const chain = table.text(constants_1.FIELDS.LANG).defaultTo('en').notNullable().comment('Language, example: en, ru, en_CA, etc');
89
- if ((opt === null || opt === void 0 ? void 0 : opt.addForeignKey) === true) {
89
+ if (opt?.addForeignKey === true) {
90
90
  table.foreign(constants_1.FIELDS.LANG).references(`language.${constants_1.FIELDS.ID}`).onUpdate('CASCADE').onDelete('CASCADE');
91
91
  }
92
- if ((opt === null || opt === void 0 ? void 0 : opt.addIndex) === true) {
92
+ if (opt?.addIndex === true) {
93
93
  table.index([constants_1.FIELDS.LANG]);
94
94
  }
95
95
  return chain;
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -28,33 +19,32 @@ const MESSAGES = {
28
19
  NO_FILENAME: 'Failed to download file as "fileName" prop was not provided and no file name was in the "url"',
29
20
  };
30
21
  const CHARSET = 'charset=';
31
- const downloadFile = (args) => __awaiter(void 0, void 0, void 0, function* () {
22
+ const downloadFile = async (args) => {
32
23
  const measureTool = new utils_1.MeasureTool();
33
- const { durationMs, result } = yield measureTool.measureExecTime('', () => __awaiter(void 0, void 0, void 0, function* () {
34
- var _a, _b, _c;
35
- if (!(args === null || args === void 0 ? void 0 : args.url)) {
24
+ const { durationMs, result } = await measureTool.measureExecTime('', async () => {
25
+ if (!args?.url) {
36
26
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, {}, MESSAGES.NO_URL);
37
27
  }
38
- const url = new url_1.URL(args === null || args === void 0 ? void 0 : args.url);
39
- const fileName = !(args === null || args === void 0 ? void 0 : args.fileName) ? url.pathname.split('/').pop() || `${url.hostname}.html` : (args === null || args === void 0 ? void 0 : args.fileName) || '';
28
+ const url = new url_1.URL(args?.url);
29
+ const fileName = !args?.fileName ? url.pathname.split('/').pop() || `${url.hostname}.html` : args?.fileName || '';
40
30
  if (!fileName) {
41
31
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, {}, MESSAGES.NO_FILENAME);
42
32
  }
43
- const fullPathName = path_1.default.resolve((args === null || args === void 0 ? void 0 : args.folder) || '', fileName);
33
+ const fullPathName = path_1.default.resolve(args?.folder || '', fileName);
44
34
  try {
45
- const response = yield axios_1.default.get(url.toString(), {
35
+ const response = await axios_1.default.get(url.toString(), {
46
36
  responseType: 'stream',
47
37
  });
48
- const strease2use = (args === null || args === void 0 ? void 0 : args.stream) || fs_1.default.createWriteStream(fullPathName);
49
- yield pipeline(response.data, strease2use);
50
- const contentType = ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[constants_1.HEADERS.CONTENT_TYPE]) || '';
38
+ const strease2use = args?.stream || fs_1.default.createWriteStream(fullPathName);
39
+ await pipeline(response.data, strease2use);
40
+ const contentType = response?.headers?.[constants_1.HEADERS.CONTENT_TYPE] || '';
51
41
  const [mimeType, charset] = contentType.split('; ');
52
- const encoding = (charset === null || charset === void 0 ? void 0 : charset.startsWith(CHARSET)) ? charset.slice(CHARSET.length) : '';
42
+ const encoding = charset?.startsWith(CHARSET) ? charset.slice(CHARSET.length) : '';
53
43
  return api_helpers_1.OpResult.ok({
54
44
  url: url.toString(),
55
45
  fileName,
56
46
  fullPathName,
57
- size: Number((_c = (_b = response.headers) === null || _b === void 0 ? void 0 : _b[constants_1.HEADERS.CONTENT_LENGTH]) !== null && _c !== void 0 ? _c : 0),
47
+ size: Number(response.headers?.[constants_1.HEADERS.CONTENT_LENGTH] ?? 0),
58
48
  mimeType,
59
49
  encoding,
60
50
  });
@@ -62,11 +52,11 @@ const downloadFile = (args) => __awaiter(void 0, void 0, void 0, function* () {
62
52
  catch (ex) {
63
53
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, { url: url.toString(), fileName, fullPathName, size: 0, mimeType: '' }, ex.message);
64
54
  }
65
- }));
55
+ });
66
56
  const data = result.getDataFirst();
67
- result.setData(Object.assign(Object.assign({}, data), { speed: (data.size * 1000) / durationMs, durationMs }));
57
+ result.setData({ ...data, speed: (data.size * 1000) / durationMs, durationMs });
68
58
  return result;
69
- });
59
+ };
70
60
  exports.downloadFile = downloadFile;
71
61
  // const run = async () => {
72
62
  // // const result = await downloadFile({
@@ -0,0 +1,88 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { Logger, MeasureTool } from '@sdflc/utils';
3
+ import { ID_TYPES } from './constants';
4
+ import { Database } from './Database';
5
+ import { BaseCorePropsInterface, BaseCoreActionsInterface, CoreActionInterface, JwtTokenSecretAndSettings, ApiContext, ExtractCredentialsArgs } from './interfaces';
6
+ declare class BaseCore {
7
+ protected measureTool: MeasureTool;
8
+ protected config: BaseCorePropsInterface;
9
+ protected logger: Logger;
10
+ constructor(props: BaseCorePropsInterface);
11
+ getIdType(): ID_TYPES;
12
+ getDb(): Database;
13
+ getRequestId(): string;
14
+ getContext(): ApiContext;
15
+ getGateways(): any;
16
+ getGateway(name?: string): any;
17
+ getValidators(): any;
18
+ success(data: any, code?: number): any;
19
+ failure(code: number, errorMsg: string, data?: any): any;
20
+ validationFailure(ex: OpResult | any): any;
21
+ exceptionFailure(ex: any, doingWhat: string, data?: any): any;
22
+ checkResult(args: any): Promise<void>;
23
+ runAction(opt: CoreActionInterface): Promise<any>;
24
+ list(args: any): Promise<any>;
25
+ get(args: any): Promise<any>;
26
+ getMany(args: any): Promise<any>;
27
+ getGatewayToSetOrerNo(): any;
28
+ getFilterToSetOrderNo(args: any): {};
29
+ create(args: any): Promise<any>;
30
+ createMany(args: any): Promise<any>;
31
+ update(args: any): Promise<any>;
32
+ updateMany(args: any): Promise<any>;
33
+ set(args: any): Promise<any>;
34
+ remove(args: any): Promise<any>;
35
+ removeMany(args: any): Promise<any>;
36
+ defaultAfterAndBefore(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
37
+ /**
38
+ * Used to transform an object before sending it in the response
39
+ * @param {any} item An object coming from the database
40
+ * @param {BaseCoreActionsInterface} opt Options
41
+ * @returns {any} transformed object
42
+ */
43
+ processItemOnOut(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
44
+ /**
45
+ * Used to transform an object before processing it on the request
46
+ * @param {any} item An object coming from the outside
47
+ * @param {BaseCoreActionsInterface} opt Options
48
+ * @returns {any} transformed object
49
+ */
50
+ processItemOnIn(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
51
+ beforeGet(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
52
+ beforeGetMany(items: any[], opt?: BaseCoreActionsInterface): Promise<any>;
53
+ beforeList(filter: any, opt?: BaseCoreActionsInterface): Promise<any>;
54
+ afterGet(item: any, opt?: BaseCoreActionsInterface): Promise<any>;
55
+ afterGetMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
56
+ afterList(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
57
+ beforeCreate(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
58
+ afterCreate(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
59
+ beforeCreateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
60
+ afterCreateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
61
+ beforeUpdate(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
62
+ afterUpdate(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
63
+ beforeUpdateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
64
+ afterUpdateMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
65
+ beforeSet(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
66
+ afterSet(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
67
+ beforeRemove(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
68
+ afterRemove(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
69
+ beforeRemoveMany(params: any, opt?: BaseCoreActionsInterface): Promise<any>;
70
+ afterRemoveMany(items: any, opt?: BaseCoreActionsInterface): Promise<any>;
71
+ onException(params: any, opt?: BaseCoreActionsInterface): Promise<string | null | undefined>;
72
+ /**
73
+ * Returns JWT secret and its settings to verify received JWT token
74
+ * @param params Object of parameters passed to the authenticate method
75
+ * @returns Object with the jwtSecret and verifyTokenArgs
76
+ */
77
+ getJwtTokenSecretAndSettings(params: any): Promise<JwtTokenSecretAndSettings>;
78
+ findSpace(): Promise<any[]>;
79
+ extractCredentials(args: ExtractCredentialsArgs): Promise<{
80
+ token: any;
81
+ fingerprint: any;
82
+ }>;
83
+ authenticate(params: any, opt?: BaseCoreActionsInterface): Promise<any[]>;
84
+ processRemovedRecord(record: any): any;
85
+ addRemovedModifierToFields(fields: string | string[]): any;
86
+ setOrderNo(args: any): Promise<void>;
87
+ }
88
+ export { BaseCore };