@sdflc/backend-helpers 1.0.48 → 1.0.51

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.
@@ -31,143 +31,97 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
31
31
  step((generator = generator.apply(thisArg, _arguments || [])).next());
32
32
  });
33
33
  };
34
- var __generator = (this && this.__generator) || function (thisArg, body) {
35
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
- function verb(n) { return function (v) { return step([n, v]); }; }
38
- function step(op) {
39
- if (f) throw new TypeError("Generator is already executing.");
40
- while (_) try {
41
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
- if (y = 0, t) op = [op[0] & 2, t.value];
43
- switch (op[0]) {
44
- case 0: case 1: t = op; break;
45
- case 4: _.label++; return { value: op[1], done: false };
46
- case 5: _.label++; y = op[1]; op = [0]; continue;
47
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
- default:
49
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
- if (t[2]) _.ops.pop();
54
- _.trys.pop(); continue;
55
- }
56
- op = body.call(thisArg, _);
57
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
- }
60
- };
61
34
  var __importDefault = (this && this.__importDefault) || function (mod) {
62
35
  return (mod && mod.__esModule) ? mod : { "default": mod };
63
36
  };
64
37
  Object.defineProperty(exports, "__esModule", { value: true });
65
38
  exports.DbMigratorAndSeeder = void 0;
66
- var path_1 = __importDefault(require("path"));
67
- var bluebird_1 = __importDefault(require("bluebird"));
68
- var lodash_1 = require("lodash");
69
- var utils_1 = require("@sdflc/utils");
70
- var SQLS = {
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 = {
71
44
  pg: {
72
- listTablesSchema: function (appSettings) { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '".concat(appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema, "';\n "); },
73
- listTables: function () { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n "; },
74
- dropTablesSchema: function (appSettings) { return "\n SELECT 'DROP TABLE IF EXISTS ".concat(appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema, ".' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '").concat(appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema, "';\n "); },
75
- dropTables: function () { return "\n SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES';\n "; },
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
+ `,
76
63
  },
77
64
  };
78
- var DbMigratorAndSeeder = /** @class */ (function () {
79
- function DbMigratorAndSeeder(knexHandle, config) {
65
+ class DbMigratorAndSeeder {
66
+ constructor(knexHandle, config) {
80
67
  this.knexHandle = knexHandle;
81
68
  this.config = config;
82
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 });
83
70
  }
84
- DbMigratorAndSeeder.prototype.runMigrations = function () {
85
- return __awaiter(this, void 0, void 0, function () {
86
- var result, version;
87
- return __generator(this, function (_a) {
88
- switch (_a.label) {
89
- case 0: return [4 /*yield*/, this.knexHandle.migrate.latest()];
90
- case 1:
91
- result = _a.sent();
92
- if (!(this.config && this.config.runDbSeed && result[1].length > 0)) return [3 /*break*/, 3];
93
- return [4 /*yield*/, this.knexHandle.seed.run()];
94
- case 2:
95
- _a.sent();
96
- _a.label = 3;
97
- case 3:
98
- this.logger.log("Ran ".concat(result[1].length, " migration(s)"));
99
- version = this.knexHandle.migrate.currentVersion();
100
- this.logger.log("Current version of database: ".concat(version));
101
- return [2 /*return*/];
102
- }
103
- });
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}`);
104
80
  });
105
- };
81
+ }
106
82
  /**
107
83
  * Go from array of objects which contain keys of object names which have an array value of seeded objects
108
84
  * to a single object with keys of object names and arrays of seeded objects
109
85
  * ie from [{table1: [], table2: [] }, { table3: [] }]
110
86
  * to { table1: [], table2: [], table3: []}
111
87
  */
112
- DbMigratorAndSeeder.prototype.transformSeedsToObject = function (generatedSeedArrays) {
113
- return (0, lodash_1.reduce)(generatedSeedArrays, function (acc, cur) {
114
- for (var key in cur) {
88
+ transformSeedsToObject(generatedSeedArrays) {
89
+ return (0, lodash_1.reduce)(generatedSeedArrays, (acc, cur) => {
90
+ for (const key in cur) {
115
91
  acc[key] = cur[key];
116
92
  }
117
93
  return acc;
118
94
  }, {});
119
- };
95
+ }
120
96
  /**
121
97
  * Drop all tables, run migrations, then seed the tables
122
98
  */
123
- DbMigratorAndSeeder.prototype.resetDb = function () {
124
- return __awaiter(this, void 0, void 0, function () {
125
- var ex_1;
126
- return __generator(this, function (_a) {
127
- switch (_a.label) {
128
- case 0:
129
- _a.trys.push([0, 3, , 4]);
130
- return [4 /*yield*/, this.wipeDb()];
131
- case 1:
132
- _a.sent();
133
- return [4 /*yield*/, this.runMigrations()];
134
- case 2:
135
- _a.sent();
136
- return [3 /*break*/, 4];
137
- case 3:
138
- ex_1 = _a.sent();
139
- this.logger.error('An exception has occurred on resetting database: ', ex_1);
140
- return [3 /*break*/, 4];
141
- case 4: return [2 /*return*/];
142
- }
143
- });
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
+ }
144
108
  });
145
- };
109
+ }
146
110
  /**
147
111
  * Selects all the tables in the schema and drops them.
148
112
  * This approach does not work in case we have constraints.
149
113
  * TODO: Remove all constraints and then drop tables.
150
114
  */
151
- DbMigratorAndSeeder.prototype.wipeDb = function () {
152
- return __awaiter(this, void 0, void 0, function () {
153
- var query, result, commands;
154
- var _this = this;
155
- return __generator(this, function (_a) {
156
- switch (_a.label) {
157
- case 0:
158
- query = this.config.dbSchema
159
- ? SQLS[this.config.dbType].dropTablesSchema(this.config)
160
- : SQLS[this.config.dbType].dropTables(this.config);
161
- return [4 /*yield*/, this.knexHandle.raw(query)];
162
- case 1:
163
- result = _a.sent();
164
- commands = result.rows.map(function (r) { return r.cmd; });
165
- bluebird_1.default.each(commands, function (cmd) { return _this.knexHandle.raw(cmd); });
166
- return [2 /*return*/];
167
- }
168
- });
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));
169
123
  });
170
- };
124
+ }
171
125
  /**
172
126
  * Removes all the records from provided list of tables
173
127
  * @param tablesToClean array of table names
@@ -175,161 +129,100 @@ var DbMigratorAndSeeder = /** @class */ (function () {
175
129
  * @param appSettings settings with db related information
176
130
  * @returns promise
177
131
  */
178
- DbMigratorAndSeeder.prototype.cleanDb = function (tablesToClean) {
179
- return __awaiter(this, void 0, void 0, function () {
180
- var idx, len;
181
- return __generator(this, function (_a) {
182
- switch (_a.label) {
183
- case 0:
184
- idx = 0, len = tablesToClean.length;
185
- _a.label = 1;
186
- case 1:
187
- if (!(idx < len)) return [3 /*break*/, 4];
188
- return [4 /*yield*/, this.cleanDbTable(tablesToClean[idx])];
189
- case 2:
190
- _a.sent();
191
- _a.label = 3;
192
- case 3:
193
- ++idx;
194
- return [3 /*break*/, 1];
195
- case 4: return [2 /*return*/, new bluebird_1.default(function (resolve) {
196
- resolve(tablesToClean);
197
- })];
198
- }
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);
199
139
  });
200
140
  });
201
- };
141
+ }
202
142
  /**
203
143
  * Removes all the records from provided table.
204
144
  * If appSettings has cleanTable object with table names then
205
145
  * it is used to add extra filters to clear the table to avoid for example users data
206
146
  * @param table Name of table from which to remove all the records
207
147
  */
208
- DbMigratorAndSeeder.prototype.cleanDbTable = function (table) {
148
+ cleanDbTable(table) {
209
149
  var _a, _b;
210
- return __awaiter(this, void 0, void 0, function () {
211
- var query, cleanTableFilters;
212
- return __generator(this, function (_c) {
213
- switch (_c.label) {
214
- case 0:
215
- query = this.knexHandle(table).withSchema(this.config.dbSchema).delete();
216
- cleanTableFilters = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.cleanTableFilters) === null || _b === void 0 ? void 0 : _b[table];
217
- if (cleanTableFilters != undefined) {
218
- if (Array.isArray(cleanTableFilters.where)) {
219
- cleanTableFilters.where.forEach(function (whereItem) {
220
- if (whereItem.fieldName) {
221
- query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
222
- }
223
- });
224
- }
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);
225
158
  }
226
- return [4 /*yield*/, query];
227
- case 1:
228
- _c.sent();
229
- return [2 /*return*/];
159
+ });
230
160
  }
231
- });
161
+ }
162
+ yield query;
232
163
  });
233
- };
164
+ }
234
165
  /**
235
166
  * Returns a list of tables in db schedm specified in settings
236
167
  * @returns arrays of table names in the provided db schema
237
168
  */
238
- DbMigratorAndSeeder.prototype.listDbTables = function () {
169
+ listDbTables() {
239
170
  var _a, _b;
240
- return __awaiter(this, void 0, void 0, function () {
241
- var skipTables, query, tables;
242
- return __generator(this, function (_c) {
243
- switch (_c.label) {
244
- case 0:
245
- skipTables = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.skipTables) !== null && _b !== void 0 ? _b : [];
246
- query = this.config.dbSchema
247
- ? SQLS[this.config.dbType].listTablesSchema(this.config)
248
- : SQLS[this.config.dbType].listTables(this.config);
249
- return [4 /*yield*/, this.knexHandle.raw(query)];
250
- case 1:
251
- tables = _c.sent();
252
- return [2 /*return*/, (tables.rows || [])
253
- .map(function (row) { return row.table_name; })
254
- .filter(function (table) { return skipTables.indexOf(table) === -1; })];
255
- }
256
- });
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);
257
180
  });
258
- };
259
- DbMigratorAndSeeder.prototype.generateSeeds = function (dirname, seedFiles) {
260
- return __awaiter(this, void 0, void 0, function () {
261
- var seedGroups, seedFileNames, seedFnExports, seedFns, seedFnsMap, i, seedFileName;
262
- return __generator(this, function (_a) {
263
- switch (_a.label) {
264
- case 0:
265
- seedGroups = [];
266
- seedFileNames = (0, lodash_1.flatten)(seedFiles);
267
- return [4 /*yield*/, Promise.all((0, lodash_1.map)(seedFileNames, function (filename) { return Promise.resolve().then(function () { return __importStar(require(path_1.default.join(dirname, "./objects/".concat(filename, ".js")))); }); }))];
268
- case 1:
269
- seedFnExports = _a.sent();
270
- seedFns = (0, lodash_1.map)(seedFnExports, 'default');
271
- seedFnsMap = {};
272
- for (i = 0; i < seedFileNames.length; i++) {
273
- seedFileName = seedFileNames[i];
274
- seedFnsMap[seedFileName] = seedFns[i];
275
- }
276
- seedFiles.reduce(function (seeds, fileGroup) {
277
- seedGroups = seedGroups.concat(fileGroup.reduce(function (group, filename) {
278
- var _a;
279
- var seedFn = seedFnsMap[filename];
280
- var seed = seedFn(seeds);
281
- var filenameCamel = (0, lodash_1.camelCase)(filename);
282
- seeds[filenameCamel] = seed;
283
- return Object.assign((_a = {}, _a[filenameCamel] = seed, _a), group);
284
- }, {}));
285
- return seeds;
286
- }, {});
287
- return [2 /*return*/, seedGroups];
288
- }
289
- });
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) => Promise.resolve().then(() => __importStar(require(path_1.default.join(dirname, `./objects/${filename}.js`))))));
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;
290
204
  });
291
- };
292
- DbMigratorAndSeeder.prototype.removeSeedsFromDb = function (seedFiles) {
293
- var tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
205
+ }
206
+ removeSeedsFromDb(seedFiles) {
207
+ const tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
294
208
  this.logger.log('Deleting records from tables: ', tablesToReset);
295
209
  return this.cleanDb(tablesToReset);
296
- };
297
- DbMigratorAndSeeder.prototype.insertRecords = function (seedGroups) {
298
- return __awaiter(this, void 0, void 0, function () {
299
- var _this = this;
300
- return __generator(this, function (_a) {
301
- this.logger.log('Inserting seeds records into tables...');
302
- return [2 /*return*/, seedGroups.reduce(function (previousGroup, group) { return __awaiter(_this, void 0, void 0, function () {
303
- var _this = this;
304
- return __generator(this, function (_a) {
305
- switch (_a.label) {
306
- case 0: return [4 /*yield*/, previousGroup];
307
- case 1:
308
- _a.sent();
309
- return [2 /*return*/, Promise.all(Object.keys(group).map(function (table) { return _this.knexHandle(table).withSchema(_this.config.dbSchema).insert(group[table]); }))];
310
- }
311
- });
312
- }); }, Promise.resolve())];
313
- });
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());
314
218
  });
315
- };
316
- DbMigratorAndSeeder.prototype.runSeeds = function (dirname, seedFiles) {
317
- return __awaiter(this, void 0, void 0, function () {
318
- var groups;
319
- return __generator(this, function (_a) {
320
- switch (_a.label) {
321
- case 0: return [4 /*yield*/, this.generateSeeds(dirname, seedFiles)];
322
- case 1:
323
- groups = _a.sent();
324
- return [4 /*yield*/, this.removeSeedsFromDb(seedFiles)];
325
- case 2:
326
- _a.sent();
327
- return [4 /*yield*/, this.insertRecords(groups)];
328
- case 3: return [2 /*return*/, _a.sent()];
329
- }
330
- });
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);
331
225
  });
332
- };
333
- return DbMigratorAndSeeder;
334
- }());
226
+ }
227
+ }
335
228
  exports.DbMigratorAndSeeder = DbMigratorAndSeeder;
@@ -0,0 +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 };