@sdflc/backend-helpers 1.0.79 → 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 (37) hide show
  1. package/build/BaseCore.js +496 -600
  2. package/build/BaseGateway.js +331 -377
  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 -184
  7. package/build/apiContext.js +35 -33
  8. package/build/baseController.js +9 -16
  9. package/build/commonValidators.js +22 -31
  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.js +496 -600
  16. package/build/esm/BaseGateway.js +331 -377
  17. package/build/esm/DataCache.js +16 -19
  18. package/build/esm/Database.js +55 -74
  19. package/build/esm/DbMigratorAndSeeder.js +88 -114
  20. package/build/esm/RedisDataLoader.js +153 -184
  21. package/build/esm/apiContext.js +35 -33
  22. package/build/esm/baseController.js +9 -16
  23. package/build/esm/commonValidators.js +22 -31
  24. package/build/esm/configBulder.js +5 -1
  25. package/build/esm/dbHelpers.js +19 -29
  26. package/build/esm/dbSeeder.js +11 -20
  27. package/build/esm/dbTableHelpers.js +10 -10
  28. package/build/esm/downloadHelpers.js +15 -25
  29. package/build/esm/knexConfigBuilder.js +17 -7
  30. package/build/esm/passwordHelpers.js +7 -16
  31. package/build/esm/resolversHelpers.js +11 -4
  32. package/build/esm/userToken.js +2 -2
  33. package/build/knexConfigBuilder.js +17 -7
  34. package/build/passwordHelpers.js +7 -16
  35. package/build/resolversHelpers.js +11 -4
  36. package/build/userToken.js +2 -2
  37. package/package.json +2 -3
@@ -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
  };
@@ -19,12 +10,16 @@ const utils_1 = require("@sdflc/utils");
19
10
  const _1 = require(".");
20
11
  const lodash_1 = require("lodash");
21
12
  class DataCache {
13
+ buildKey;
14
+ loader;
15
+ config;
16
+ redisClient;
22
17
  constructor(props) {
23
18
  const { loaderFn, keyPrefix, context, buildKey, redisClient, table } = props || {};
24
- if (!(props === null || props === void 0 ? void 0 : props.idField)) {
19
+ if (!props?.idField) {
25
20
  props.idField = _1.FIELDS.ID;
26
21
  }
27
- if (!(props === null || props === void 0 ? void 0 : props.idFieldAs)) {
22
+ if (!props?.idFieldAs) {
28
23
  props.idFieldAs = _1.FIELDS.ID;
29
24
  }
30
25
  this.config = props;
@@ -32,7 +27,7 @@ class DataCache {
32
27
  this.buildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
33
28
  this.batchLoaderDefault = this.batchLoaderDefault.bind(this);
34
29
  const fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(props);
35
- const prefixToUse = (context === null || context === void 0 ? void 0 : context.keyPrefix) || keyPrefix || table;
30
+ const prefixToUse = context?.keyPrefix || keyPrefix || table;
36
31
  this.init(fn, prefixToUse, context);
37
32
  }
38
33
  batchLoaderDefault(props) {
@@ -46,9 +41,12 @@ class DataCache {
46
41
  else if (!db) {
47
42
  throw Error(`DataCache requires 'db' property to be setup`);
48
43
  }
49
- return (ids) => __awaiter(this, void 0, void 0, function* () {
44
+ return async (ids) => {
50
45
  const resultItems = [];
51
- const readCfg = Object.assign(Object.assign({}, props), { buildKey: this.buildKey });
46
+ const readCfg = {
47
+ ...props,
48
+ buildKey: this.buildKey,
49
+ };
52
50
  const idsToUse = (0, lodash_1.castArray)(ids);
53
51
  if (!readAll) {
54
52
  readCfg.mapBy = idFieldAs || idField;
@@ -57,7 +55,7 @@ class DataCache {
57
55
  values: idsToUse.filter((id) => id),
58
56
  };
59
57
  }
60
- const dbItems = yield db.read(readCfg);
58
+ const dbItems = await db.read(readCfg);
61
59
  if (readAll) {
62
60
  resultItems.push(...dbItems);
63
61
  }
@@ -65,7 +63,7 @@ class DataCache {
65
63
  resultItems.push(...idsToUse.map((id) => dbItems[this.buildKey(id)] || null));
66
64
  }
67
65
  return resultItems;
68
- });
66
+ };
69
67
  }
70
68
  init(batchFunction, keyPrefix, context) {
71
69
  if (this.redisClient) {
@@ -92,12 +90,11 @@ class DataCache {
92
90
  return this.loader.loadMany(keys.map((key) => this.buildKey(key)));
93
91
  }
94
92
  clear(key) {
95
- var _a;
96
93
  if (Array.isArray(key)) {
97
- key.forEach((item) => { var _a; return (_a = this.loader) === null || _a === void 0 ? void 0 : _a.clear(this.buildKey(item)); });
94
+ key.forEach((item) => this.loader?.clear(this.buildKey(item)));
98
95
  }
99
96
  else {
100
- (_a = this.loader) === null || _a === void 0 ? void 0 : _a.clear(this.buildKey(key));
97
+ this.loader?.clear(this.buildKey(key));
101
98
  }
102
99
  }
103
100
  }
package/build/Database.js CHANGED
@@ -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
  };
@@ -24,11 +15,11 @@ const buildKey = (args) => {
24
15
  return parts.join('|');
25
16
  };
26
17
  class Database {
18
+ trx = null;
19
+ knexHandle = null;
20
+ dbSchema = '';
21
+ logger = new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
27
22
  constructor(props) {
28
- this.trx = null;
29
- this.knexHandle = null;
30
- this.dbSchema = '';
31
- this.logger = new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
32
23
  if (!props.knexConfig) {
33
24
  throw new Error('The Database class expects to have `knexConfig` in its constructor props');
34
25
  }
@@ -79,43 +70,35 @@ class Database {
79
70
  raw(query, bindings) {
80
71
  return this.knexHandle.raw(query, bindings);
81
72
  }
82
- runRawQuery(query, bindings) {
83
- return __awaiter(this, void 0, void 0, function* () {
84
- const rows = yield (this.trx ? this.trx : this.knexHandle).raw(query, bindings);
85
- return rows;
86
- });
73
+ async runRawQuery(query, bindings) {
74
+ const rows = await (this.trx ? this.trx : this.knexHandle).raw(query, bindings);
75
+ return rows;
87
76
  }
88
- startTransaction() {
89
- return __awaiter(this, void 0, void 0, function* () {
90
- const trx = yield this.createTransaction(this.trx);
91
- this.trx = trx;
92
- return trx;
93
- });
77
+ async startTransaction() {
78
+ const trx = await this.createTransaction(this.trx);
79
+ this.trx = trx;
80
+ return trx;
94
81
  }
95
82
  setTransaction(trx) {
96
83
  this.trx = trx;
97
84
  }
98
- commitTransaction() {
99
- return __awaiter(this, void 0, void 0, function* () {
100
- if (this.trx) {
101
- yield this.trx.commit();
102
- this.trx = undefined;
103
- }
104
- });
85
+ async commitTransaction() {
86
+ if (this.trx) {
87
+ await this.trx.commit();
88
+ this.trx = undefined;
89
+ }
105
90
  }
106
- rollbackTransaction() {
107
- return __awaiter(this, void 0, void 0, function* () {
108
- if (this.trx) {
109
- try {
110
- yield this.trx.rollback();
111
- }
112
- catch (ex) {
113
- // Do nothing here
114
- this.logger.error(`Failed to rollback a transaction:`, ex.message);
115
- }
91
+ async rollbackTransaction() {
92
+ if (this.trx) {
93
+ try {
94
+ await this.trx.rollback();
116
95
  }
117
- this.trx = undefined;
118
- });
96
+ catch (ex) {
97
+ // Do nothing here
98
+ this.logger.error(`Failed to rollback a transaction:`, ex.message);
99
+ }
100
+ }
101
+ this.trx = undefined;
119
102
  }
120
103
  doCalculated(item, calculatedFields) {
121
104
  calculatedFields.forEach((calcField) => {
@@ -124,40 +107,38 @@ class Database {
124
107
  }
125
108
  });
126
109
  }
127
- read(args) {
128
- return __awaiter(this, void 0, void 0, function* () {
129
- const { where, whereIn, extendQuery, table, selectFields, mapBy, calculated, buildKey } = args || {};
130
- const query = this.getBuilder(table).select(Array.isArray(selectFields) && selectFields.length > 0 ? selectFields : '*');
131
- if (where) {
132
- query.where(where);
133
- }
134
- if (whereIn) {
135
- query.whereIn(whereIn.field, whereIn.values);
136
- }
137
- if (typeof extendQuery === 'function') {
138
- yield extendQuery(query);
139
- }
140
- let dbResults = yield query;
141
- if (mapBy) {
142
- const fnBuildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
143
- dbResults = dbResults.reduce((acc, item) => {
144
- const key = fnBuildKey(item[(0, lodash_1.camelCase)(mapBy)]);
145
- if (Array.isArray(calculated) && calculated.length > 0) {
146
- this.doCalculated(item, calculated);
147
- }
148
- acc[key] = item;
149
- return acc;
150
- }, {});
151
- }
152
- else {
110
+ async read(args) {
111
+ const { where, whereIn, extendQuery, table, selectFields, mapBy, calculated, buildKey } = args || {};
112
+ const query = this.getBuilder(table).select(Array.isArray(selectFields) && selectFields.length > 0 ? selectFields : '*');
113
+ if (where) {
114
+ query.where(where);
115
+ }
116
+ if (whereIn) {
117
+ query.whereIn(whereIn.field, whereIn.values);
118
+ }
119
+ if (typeof extendQuery === 'function') {
120
+ await extendQuery(query);
121
+ }
122
+ let dbResults = await query;
123
+ if (mapBy) {
124
+ const fnBuildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
125
+ dbResults = dbResults.reduce((acc, item) => {
126
+ const key = fnBuildKey(item[(0, lodash_1.camelCase)(mapBy)]);
153
127
  if (Array.isArray(calculated) && calculated.length > 0) {
154
- dbResults.forEach((row) => {
155
- this.doCalculated(row, calculated);
156
- });
128
+ this.doCalculated(item, calculated);
157
129
  }
130
+ acc[key] = item;
131
+ return acc;
132
+ }, {});
133
+ }
134
+ else {
135
+ if (Array.isArray(calculated) && calculated.length > 0) {
136
+ dbResults.forEach((row) => {
137
+ this.doCalculated(row, calculated);
138
+ });
158
139
  }
159
- return dbResults;
160
- });
140
+ }
141
+ return dbResults;
161
142
  }
162
143
  createSortBy(sortBy, defaultSortBy) {
163
144
  if (!sortBy) {
@@ -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
  };
@@ -55,16 +46,16 @@ const SQLS = {
55
46
  listTablesSchema: (appSettings) => `
56
47
  SELECT TABLE_NAME as table_name
57
48
  FROM INFORMATION_SCHEMA.TABLES
58
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
49
+ WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
59
50
  `,
60
51
  listTables: () => `
61
52
  SELECT TABLE_NAME as table_name
62
53
  FROM INFORMATION_SCHEMA.TABLES
63
54
  `,
64
55
  dropTablesSchema: (appSettings) => `
65
- SELECT 'DROP TABLE IF EXISTS ${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}.' || TABLE_NAME || ';' as cmd
56
+ SELECT 'DROP TABLE IF EXISTS ${appSettings?.dbSchema}.' || TABLE_NAME || ';' as cmd
66
57
  FROM INFORMATION_SCHEMA.TABLES
67
- WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
58
+ WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
68
59
  `,
69
60
  dropTables: () => `
70
61
  SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd
@@ -73,21 +64,22 @@ const SQLS = {
73
64
  },
74
65
  };
75
66
  class DbMigratorAndSeeder {
67
+ knexHandle;
68
+ config;
69
+ logger;
76
70
  constructor(knexHandle, config) {
77
71
  this.knexHandle = knexHandle;
78
72
  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 });
73
+ this.logger = config?.logger instanceof utils_1.Logger ? config.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.LOG });
80
74
  }
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
- });
75
+ async runMigrations() {
76
+ const result = await this.knexHandle.migrate.latest();
77
+ if (this.config && this.config.runDbSeed && result[1].length > 0) {
78
+ await this.knexHandle.seed.run();
79
+ }
80
+ this.logger.log(`Ran ${result[1].length} migration(s)`);
81
+ const version = this.knexHandle.migrate.currentVersion();
82
+ this.logger.log(`Current version of database: ${version}`);
91
83
  }
92
84
  /**
93
85
  * Go from array of objects which contain keys of object names which have an array value of seeded objects
@@ -106,31 +98,27 @@ class DbMigratorAndSeeder {
106
98
  /**
107
99
  * Drop all tables, run migrations, then seed the tables
108
100
  */
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
- });
101
+ async resetDb() {
102
+ try {
103
+ await this.wipeDb();
104
+ await this.runMigrations();
105
+ }
106
+ catch (ex) {
107
+ this.logger.error('An exception has occurred on resetting database: ', ex);
108
+ }
119
109
  }
120
110
  /**
121
111
  * Selects all the tables in the schema and drops them.
122
112
  * This approach does not work in case we have constraints.
123
113
  * TODO: Remove all constraints and then drop tables.
124
114
  */
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
- });
115
+ async wipeDb() {
116
+ const query = this.config.dbSchema
117
+ ? SQLS[this.config.dbType].dropTablesSchema(this.config)
118
+ : SQLS[this.config.dbType].dropTables(this.config);
119
+ const result = await this.knexHandle.raw(query);
120
+ const commands = result.rows.map((r) => r.cmd);
121
+ bluebird_1.default.each(commands, (cmd) => this.knexHandle.raw(cmd));
134
122
  }
135
123
  /**
136
124
  * Removes all the records from provided list of tables
@@ -139,14 +127,12 @@ class DbMigratorAndSeeder {
139
127
  * @param appSettings settings with db related information
140
128
  * @returns promise
141
129
  */
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
- });
130
+ async cleanDb(tablesToClean) {
131
+ for (let idx = 0, len = tablesToClean.length; idx < len; ++idx) {
132
+ await this.cleanDbTable(tablesToClean[idx]);
133
+ }
134
+ return new bluebird_1.default((resolve) => {
135
+ resolve(tablesToClean);
150
136
  });
151
137
  }
152
138
  /**
@@ -155,84 +141,72 @@ class DbMigratorAndSeeder {
155
141
  * it is used to add extra filters to clear the table to avoid for example users data
156
142
  * @param table Name of table from which to remove all the records
157
143
  */
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
- }
144
+ async cleanDbTable(table) {
145
+ const query = this.knexHandle(table).withSchema(this.config.dbSchema).delete();
146
+ const cleanTableFilters = this.config?.cleanTableFilters?.[table];
147
+ if (cleanTableFilters != undefined) {
148
+ if (Array.isArray(cleanTableFilters.where)) {
149
+ cleanTableFilters.where.forEach((whereItem) => {
150
+ if (whereItem.fieldName) {
151
+ query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
152
+ }
153
+ });
171
154
  }
172
- yield query;
173
- });
155
+ }
156
+ await query;
174
157
  }
175
158
  /**
176
159
  * Returns a list of tables in db schedm specified in settings
177
160
  * @returns arrays of table names in the provided db schema
178
161
  */
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
- });
162
+ async listDbTables() {
163
+ const skipTables = this.config?.skipTables ?? [];
164
+ const query = this.config.dbSchema
165
+ ? SQLS[this.config.dbType].listTablesSchema(this.config)
166
+ : SQLS[this.config.dbType].listTables(this.config);
167
+ const tables = await this.knexHandle.raw(query);
168
+ return (tables.rows || [])
169
+ .map((row) => row.table_name)
170
+ .filter((table) => skipTables.indexOf(table) === -1);
191
171
  }
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
- });
172
+ async generateSeeds(dirname, seedFiles) {
173
+ let seedGroups = [];
174
+ const seedFileNames = (0, lodash_1.flatten)(seedFiles);
175
+ 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)))));
176
+ const seedFns = (0, lodash_1.map)(seedFnExports, 'default');
177
+ const seedFnsMap = {};
178
+ for (let i = 0; i < seedFileNames.length; i++) {
179
+ const seedFileName = seedFileNames[i];
180
+ seedFnsMap[seedFileName] = seedFns[i];
181
+ }
182
+ seedFiles.reduce((seeds, fileGroup) => {
183
+ seedGroups = seedGroups.concat(fileGroup.reduce((group, filename) => {
184
+ const seedFn = seedFnsMap[filename];
185
+ const seed = seedFn(seeds);
186
+ const filenameCamel = (0, lodash_1.camelCase)(filename);
187
+ seeds[filenameCamel] = seed;
188
+ return Object.assign({ [filenameCamel]: seed }, group);
189
+ }, {}));
190
+ return seeds;
191
+ }, {});
192
+ return seedGroups;
215
193
  }
216
194
  removeSeedsFromDb(seedFiles) {
217
195
  const tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
218
196
  this.logger.log('Deleting records from tables: ', tablesToReset);
219
197
  return this.cleanDb(tablesToReset);
220
198
  }
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
- });
199
+ async insertRecords(seedGroups) {
200
+ this.logger.log('Inserting seeds records into tables...');
201
+ return seedGroups.reduce(async (previousGroup, group) => {
202
+ await previousGroup;
203
+ return Promise.all(Object.keys(group).map((table) => this.knexHandle(table).withSchema(this.config.dbSchema).insert(group[table])));
204
+ }, Promise.resolve());
229
205
  }
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
- });
206
+ async runSeeds(dirname, seedFiles) {
207
+ const groups = await this.generateSeeds(dirname, seedFiles);
208
+ await this.removeSeedsFromDb(seedFiles);
209
+ return await this.insertRecords(groups);
236
210
  }
237
211
  }
238
212
  exports.DbMigratorAndSeeder = DbMigratorAndSeeder;