@sdflc/backend-helpers 1.0.76 → 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 -483
  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,228 +1,238 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.DbMigratorAndSeeder = void 0;
39
- const path_1 = __importDefault(require("path"));
40
- const bluebird_1 = __importDefault(require("bluebird"));
41
- const lodash_1 = require("lodash");
42
- const utils_1 = require("@sdflc/utils");
43
- const SQLS = {
44
- pg: {
45
- listTablesSchema: (appSettings) => `
46
- SELECT TABLE_NAME as table_name
47
- FROM INFORMATION_SCHEMA.TABLES
48
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
49
- `,
50
- listTables: () => `
51
- SELECT TABLE_NAME as table_name
52
- FROM INFORMATION_SCHEMA.TABLES
53
- `,
54
- dropTablesSchema: (appSettings) => `
55
- SELECT 'DROP TABLE IF EXISTS ${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}.' || TABLE_NAME || ';' as cmd
56
- FROM INFORMATION_SCHEMA.TABLES
57
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
58
- `,
59
- dropTables: () => `
60
- SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd
61
- FROM INFORMATION_SCHEMA.TABLES';
62
- `,
63
- },
64
- };
65
- class DbMigratorAndSeeder {
66
- constructor(knexHandle, config) {
67
- this.knexHandle = knexHandle;
68
- this.config = config;
69
- this.logger = (config === null || config === void 0 ? void 0 : config.logger) instanceof utils_1.Logger ? config.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.LOG });
70
- }
71
- runMigrations() {
72
- return __awaiter(this, void 0, void 0, function* () {
73
- const result = yield this.knexHandle.migrate.latest();
74
- if (this.config && this.config.runDbSeed && result[1].length > 0) {
75
- yield this.knexHandle.seed.run();
76
- }
77
- this.logger.log(`Ran ${result[1].length} migration(s)`);
78
- const version = this.knexHandle.migrate.currentVersion();
79
- this.logger.log(`Current version of database: ${version}`);
80
- });
81
- }
82
- /**
83
- * Go from array of objects which contain keys of object names which have an array value of seeded objects
84
- * to a single object with keys of object names and arrays of seeded objects
85
- * ie from [{table1: [], table2: [] }, { table3: [] }]
86
- * to { table1: [], table2: [], table3: []}
87
- */
88
- transformSeedsToObject(generatedSeedArrays) {
89
- return (0, lodash_1.reduce)(generatedSeedArrays, (acc, cur) => {
90
- for (const key in cur) {
91
- acc[key] = cur[key];
92
- }
93
- return acc;
94
- }, {});
95
- }
96
- /**
97
- * Drop all tables, run migrations, then seed the tables
98
- */
99
- resetDb() {
100
- return __awaiter(this, void 0, void 0, function* () {
101
- try {
102
- yield this.wipeDb();
103
- yield this.runMigrations();
104
- }
105
- catch (ex) {
106
- this.logger.error('An exception has occurred on resetting database: ', ex);
107
- }
108
- });
109
- }
110
- /**
111
- * Selects all the tables in the schema and drops them.
112
- * This approach does not work in case we have constraints.
113
- * TODO: Remove all constraints and then drop tables.
114
- */
115
- wipeDb() {
116
- return __awaiter(this, void 0, void 0, function* () {
117
- const query = this.config.dbSchema
118
- ? SQLS[this.config.dbType].dropTablesSchema(this.config)
119
- : SQLS[this.config.dbType].dropTables(this.config);
120
- const result = yield this.knexHandle.raw(query);
121
- const commands = result.rows.map((r) => r.cmd);
122
- bluebird_1.default.each(commands, (cmd) => this.knexHandle.raw(cmd));
123
- });
124
- }
125
- /**
126
- * Removes all the records from provided list of tables
127
- * @param tablesToClean array of table names
128
- * @param knexHandle Knex handle object with configured connection to DB
129
- * @param appSettings settings with db related information
130
- * @returns promise
131
- */
132
- cleanDb(tablesToClean) {
133
- return __awaiter(this, void 0, void 0, function* () {
134
- for (let idx = 0, len = tablesToClean.length; idx < len; ++idx) {
135
- yield this.cleanDbTable(tablesToClean[idx]);
136
- }
137
- return new bluebird_1.default((resolve) => {
138
- resolve(tablesToClean);
139
- });
140
- });
141
- }
142
- /**
143
- * Removes all the records from provided table.
144
- * If appSettings has cleanTable object with table names then
145
- * it is used to add extra filters to clear the table to avoid for example users data
146
- * @param table Name of table from which to remove all the records
147
- */
148
- cleanDbTable(table) {
149
- var _a, _b;
150
- return __awaiter(this, void 0, void 0, function* () {
151
- const query = this.knexHandle(table).withSchema(this.config.dbSchema).delete();
152
- const cleanTableFilters = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.cleanTableFilters) === null || _b === void 0 ? void 0 : _b[table];
153
- if (cleanTableFilters != undefined) {
154
- if (Array.isArray(cleanTableFilters.where)) {
155
- cleanTableFilters.where.forEach((whereItem) => {
156
- if (whereItem.fieldName) {
157
- query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
158
- }
159
- });
160
- }
161
- }
162
- yield query;
163
- });
164
- }
165
- /**
166
- * Returns a list of tables in db schedm specified in settings
167
- * @returns arrays of table names in the provided db schema
168
- */
169
- listDbTables() {
170
- var _a, _b;
171
- return __awaiter(this, void 0, void 0, function* () {
172
- const skipTables = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.skipTables) !== null && _b !== void 0 ? _b : [];
173
- const query = this.config.dbSchema
174
- ? SQLS[this.config.dbType].listTablesSchema(this.config)
175
- : SQLS[this.config.dbType].listTables(this.config);
176
- const tables = yield this.knexHandle.raw(query);
177
- return (tables.rows || [])
178
- .map((row) => row.table_name)
179
- .filter((table) => skipTables.indexOf(table) === -1);
180
- });
181
- }
182
- generateSeeds(dirname, seedFiles) {
183
- return __awaiter(this, void 0, void 0, function* () {
184
- let seedGroups = [];
185
- const seedFileNames = (0, lodash_1.flatten)(seedFiles);
186
- const seedFnExports = yield Promise.all((0, lodash_1.map)(seedFileNames, (filename) => { var _a; return _a = path_1.default.join(dirname, `./objects/${filename}.js`), Promise.resolve().then(() => __importStar(require(_a))); }));
187
- const seedFns = (0, lodash_1.map)(seedFnExports, 'default');
188
- const seedFnsMap = {};
189
- for (let i = 0; i < seedFileNames.length; i++) {
190
- const seedFileName = seedFileNames[i];
191
- seedFnsMap[seedFileName] = seedFns[i];
192
- }
193
- seedFiles.reduce((seeds, fileGroup) => {
194
- seedGroups = seedGroups.concat(fileGroup.reduce((group, filename) => {
195
- const seedFn = seedFnsMap[filename];
196
- const seed = seedFn(seeds);
197
- const filenameCamel = (0, lodash_1.camelCase)(filename);
198
- seeds[filenameCamel] = seed;
199
- return Object.assign({ [filenameCamel]: seed }, group);
200
- }, {}));
201
- return seeds;
202
- }, {});
203
- return seedGroups;
204
- });
205
- }
206
- removeSeedsFromDb(seedFiles) {
207
- const tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
208
- this.logger.log('Deleting records from tables: ', tablesToReset);
209
- return this.cleanDb(tablesToReset);
210
- }
211
- insertRecords(seedGroups) {
212
- return __awaiter(this, void 0, void 0, function* () {
213
- this.logger.log('Inserting seeds records into tables...');
214
- return seedGroups.reduce((previousGroup, group) => __awaiter(this, void 0, void 0, function* () {
215
- yield previousGroup;
216
- return Promise.all(Object.keys(group).map((table) => this.knexHandle(table).withSchema(this.config.dbSchema).insert(group[table])));
217
- }), Promise.resolve());
218
- });
219
- }
220
- runSeeds(dirname, seedFiles) {
221
- return __awaiter(this, void 0, void 0, function* () {
222
- const groups = yield this.generateSeeds(dirname, seedFiles);
223
- yield this.removeSeedsFromDb(seedFiles);
224
- return yield this.insertRecords(groups);
225
- });
226
- }
227
- }
228
- exports.DbMigratorAndSeeder = DbMigratorAndSeeder;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.DbMigratorAndSeeder = void 0;
49
+ const path_1 = __importDefault(require("path"));
50
+ const bluebird_1 = __importDefault(require("bluebird"));
51
+ const lodash_1 = require("lodash");
52
+ const utils_1 = require("@sdflc/utils");
53
+ const SQLS = {
54
+ pg: {
55
+ listTablesSchema: (appSettings) => `
56
+ SELECT TABLE_NAME as table_name
57
+ FROM INFORMATION_SCHEMA.TABLES
58
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
59
+ `,
60
+ listTables: () => `
61
+ SELECT TABLE_NAME as table_name
62
+ FROM INFORMATION_SCHEMA.TABLES
63
+ `,
64
+ dropTablesSchema: (appSettings) => `
65
+ SELECT 'DROP TABLE IF EXISTS ${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}.' || TABLE_NAME || ';' as cmd
66
+ FROM INFORMATION_SCHEMA.TABLES
67
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
68
+ `,
69
+ dropTables: () => `
70
+ SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd
71
+ FROM INFORMATION_SCHEMA.TABLES';
72
+ `,
73
+ },
74
+ };
75
+ class DbMigratorAndSeeder {
76
+ constructor(knexHandle, config) {
77
+ this.knexHandle = knexHandle;
78
+ this.config = config;
79
+ this.logger = (config === null || config === void 0 ? void 0 : config.logger) instanceof utils_1.Logger ? config.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.LOG });
80
+ }
81
+ runMigrations() {
82
+ return __awaiter(this, void 0, void 0, function* () {
83
+ const result = yield this.knexHandle.migrate.latest();
84
+ if (this.config && this.config.runDbSeed && result[1].length > 0) {
85
+ yield this.knexHandle.seed.run();
86
+ }
87
+ this.logger.log(`Ran ${result[1].length} migration(s)`);
88
+ const version = this.knexHandle.migrate.currentVersion();
89
+ this.logger.log(`Current version of database: ${version}`);
90
+ });
91
+ }
92
+ /**
93
+ * Go from array of objects which contain keys of object names which have an array value of seeded objects
94
+ * to a single object with keys of object names and arrays of seeded objects
95
+ * ie from [{table1: [], table2: [] }, { table3: [] }]
96
+ * to { table1: [], table2: [], table3: []}
97
+ */
98
+ transformSeedsToObject(generatedSeedArrays) {
99
+ return (0, lodash_1.reduce)(generatedSeedArrays, (acc, cur) => {
100
+ for (const key in cur) {
101
+ acc[key] = cur[key];
102
+ }
103
+ return acc;
104
+ }, {});
105
+ }
106
+ /**
107
+ * Drop all tables, run migrations, then seed the tables
108
+ */
109
+ resetDb() {
110
+ return __awaiter(this, void 0, void 0, function* () {
111
+ try {
112
+ yield this.wipeDb();
113
+ yield this.runMigrations();
114
+ }
115
+ catch (ex) {
116
+ this.logger.error('An exception has occurred on resetting database: ', ex);
117
+ }
118
+ });
119
+ }
120
+ /**
121
+ * Selects all the tables in the schema and drops them.
122
+ * This approach does not work in case we have constraints.
123
+ * TODO: Remove all constraints and then drop tables.
124
+ */
125
+ wipeDb() {
126
+ return __awaiter(this, void 0, void 0, function* () {
127
+ const query = this.config.dbSchema
128
+ ? SQLS[this.config.dbType].dropTablesSchema(this.config)
129
+ : SQLS[this.config.dbType].dropTables(this.config);
130
+ const result = yield this.knexHandle.raw(query);
131
+ const commands = result.rows.map((r) => r.cmd);
132
+ bluebird_1.default.each(commands, (cmd) => this.knexHandle.raw(cmd));
133
+ });
134
+ }
135
+ /**
136
+ * Removes all the records from provided list of tables
137
+ * @param tablesToClean array of table names
138
+ * @param knexHandle Knex handle object with configured connection to DB
139
+ * @param appSettings settings with db related information
140
+ * @returns promise
141
+ */
142
+ cleanDb(tablesToClean) {
143
+ return __awaiter(this, void 0, void 0, function* () {
144
+ for (let idx = 0, len = tablesToClean.length; idx < len; ++idx) {
145
+ yield this.cleanDbTable(tablesToClean[idx]);
146
+ }
147
+ return new bluebird_1.default((resolve) => {
148
+ resolve(tablesToClean);
149
+ });
150
+ });
151
+ }
152
+ /**
153
+ * Removes all the records from provided table.
154
+ * If appSettings has cleanTable object with table names then
155
+ * it is used to add extra filters to clear the table to avoid for example users data
156
+ * @param table Name of table from which to remove all the records
157
+ */
158
+ cleanDbTable(table) {
159
+ return __awaiter(this, void 0, void 0, function* () {
160
+ var _a, _b;
161
+ const query = this.knexHandle(table).withSchema(this.config.dbSchema).delete();
162
+ const cleanTableFilters = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.cleanTableFilters) === null || _b === void 0 ? void 0 : _b[table];
163
+ if (cleanTableFilters != undefined) {
164
+ if (Array.isArray(cleanTableFilters.where)) {
165
+ cleanTableFilters.where.forEach((whereItem) => {
166
+ if (whereItem.fieldName) {
167
+ query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
168
+ }
169
+ });
170
+ }
171
+ }
172
+ yield query;
173
+ });
174
+ }
175
+ /**
176
+ * Returns a list of tables in db schedm specified in settings
177
+ * @returns arrays of table names in the provided db schema
178
+ */
179
+ listDbTables() {
180
+ return __awaiter(this, void 0, void 0, function* () {
181
+ var _a, _b;
182
+ const skipTables = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.skipTables) !== null && _b !== void 0 ? _b : [];
183
+ const query = this.config.dbSchema
184
+ ? SQLS[this.config.dbType].listTablesSchema(this.config)
185
+ : SQLS[this.config.dbType].listTables(this.config);
186
+ const tables = yield this.knexHandle.raw(query);
187
+ return (tables.rows || [])
188
+ .map((row) => row.table_name)
189
+ .filter((table) => skipTables.indexOf(table) === -1);
190
+ });
191
+ }
192
+ generateSeeds(dirname, seedFiles) {
193
+ return __awaiter(this, void 0, void 0, function* () {
194
+ let seedGroups = [];
195
+ const seedFileNames = (0, lodash_1.flatten)(seedFiles);
196
+ 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)))));
197
+ const seedFns = (0, lodash_1.map)(seedFnExports, 'default');
198
+ const seedFnsMap = {};
199
+ for (let i = 0; i < seedFileNames.length; i++) {
200
+ const seedFileName = seedFileNames[i];
201
+ seedFnsMap[seedFileName] = seedFns[i];
202
+ }
203
+ seedFiles.reduce((seeds, fileGroup) => {
204
+ seedGroups = seedGroups.concat(fileGroup.reduce((group, filename) => {
205
+ const seedFn = seedFnsMap[filename];
206
+ const seed = seedFn(seeds);
207
+ const filenameCamel = (0, lodash_1.camelCase)(filename);
208
+ seeds[filenameCamel] = seed;
209
+ return Object.assign({ [filenameCamel]: seed }, group);
210
+ }, {}));
211
+ return seeds;
212
+ }, {});
213
+ return seedGroups;
214
+ });
215
+ }
216
+ removeSeedsFromDb(seedFiles) {
217
+ const tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
218
+ this.logger.log('Deleting records from tables: ', tablesToReset);
219
+ return this.cleanDb(tablesToReset);
220
+ }
221
+ insertRecords(seedGroups) {
222
+ return __awaiter(this, void 0, void 0, function* () {
223
+ this.logger.log('Inserting seeds records into tables...');
224
+ return seedGroups.reduce((previousGroup, group) => __awaiter(this, void 0, void 0, function* () {
225
+ yield previousGroup;
226
+ return Promise.all(Object.keys(group).map((table) => this.knexHandle(table).withSchema(this.config.dbSchema).insert(group[table])));
227
+ }), Promise.resolve());
228
+ });
229
+ }
230
+ runSeeds(dirname, seedFiles) {
231
+ return __awaiter(this, void 0, void 0, function* () {
232
+ const groups = yield this.generateSeeds(dirname, seedFiles);
233
+ yield this.removeSeedsFromDb(seedFiles);
234
+ return yield this.insertRecords(groups);
235
+ });
236
+ }
237
+ }
238
+ exports.DbMigratorAndSeeder = DbMigratorAndSeeder;
@@ -1,41 +1,41 @@
1
- declare class RedisDataLoader {
2
- private opt?;
3
- private dataLoaderOpt?;
4
- private keySpace;
5
- private loader?;
6
- private redisClient;
7
- private static messages;
8
- constructor(redisClient: any, keySpace?: string, userLoader?: any, opt?: any);
9
- /**
10
- * Adds a prefix to the passed key
11
- * @param key Key value
12
- * @returns Trasnformed key value that includes key space
13
- */
14
- makeKey(key: string): string;
15
- /**
16
- * Deserializes response from Readis
17
- * @param str String to deserialize
18
- * @returns
19
- */
20
- parse(str: any): Promise<any>;
21
- /**
22
- * Serializes passed value to a string
23
- * @param value A value to be serialized
24
- * @returns serialized value in the form of string
25
- */
26
- toString(value: any): Promise<string>;
27
- rSetAndGet(key: string, rawValue: any): Promise<any>;
28
- rMSetAndGet(keys: string[], rawValues: any[]): Promise<any[]>;
29
- rGet(key: string): Promise<any>;
30
- rMGet(keys: string[]): Promise<any[]>;
31
- rSet(key: string, rawValue: any): Promise<any>;
32
- rMSet(keys: string[], values: any[]): Promise<any>;
33
- rDel(key: string): Promise<any>;
34
- load(key: string): Promise<any>;
35
- loadMany(keys: string[]): Promise<any>;
36
- prime(key: string, value: any): Promise<any>;
37
- clear(key: string): Promise<any>;
38
- clearAllLocal(): Promise<any>;
39
- clearLocal(key: string): Promise<any>;
40
- }
41
- export { RedisDataLoader };
1
+ declare class RedisDataLoader {
2
+ private opt?;
3
+ private dataLoaderOpt?;
4
+ private keySpace;
5
+ private loader?;
6
+ private redisClient;
7
+ private static messages;
8
+ constructor(redisClient: any, keySpace?: string, userLoader?: any, opt?: any);
9
+ /**
10
+ * Adds a prefix to the passed key
11
+ * @param key Key value
12
+ * @returns Trasnformed key value that includes key space
13
+ */
14
+ makeKey(key: string): string;
15
+ /**
16
+ * Deserializes response from Readis
17
+ * @param str String to deserialize
18
+ * @returns
19
+ */
20
+ parse(str: any): Promise<any>;
21
+ /**
22
+ * Serializes passed value to a string
23
+ * @param value A value to be serialized
24
+ * @returns serialized value in the form of string
25
+ */
26
+ toString(value: any): Promise<string>;
27
+ rSetAndGet(key: string, rawValue: any): Promise<any>;
28
+ rMSetAndGet(keys: string[], rawValues: any[]): Promise<any[]>;
29
+ rGet(key: string): Promise<any>;
30
+ rMGet(keys: string[]): Promise<any[]>;
31
+ rSet(key: string, rawValue: any): Promise<any>;
32
+ rMSet(keys: string[], values: any[]): Promise<any>;
33
+ rDel(key: string): Promise<any>;
34
+ load(key: string): Promise<any>;
35
+ loadMany(keys: string[]): Promise<any>;
36
+ prime(key: string, value: any): Promise<any>;
37
+ clear(key: string): Promise<any>;
38
+ clearAllLocal(): Promise<any>;
39
+ clearLocal(key: string): Promise<any>;
40
+ }
41
+ export { RedisDataLoader };