@sdflc/backend-helpers 1.0.49 → 1.0.52

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.
@@ -8,113 +8,71 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- 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;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
11
  Object.defineProperty(exports, "__esModule", { value: true });
39
12
  exports.validateUpdate = exports.validateCreate = exports.validateList = exports.shouldHaveId = exports.shouldHaveParams = void 0;
40
- var api_helpers_1 = require("@sdflc/api-helpers");
41
- var checkItHelpers_1 = require("./checkItHelpers");
42
- var shouldHaveParams = function (args) {
43
- var keys = Object.keys(args || {});
13
+ const api_helpers_1 = require("@sdflc/api-helpers");
14
+ const checkItHelpers_1 = require("./checkItHelpers");
15
+ const shouldHaveParams = (args) => {
16
+ const keys = Object.keys(args || {});
44
17
  if (keys.length === 0) {
45
- var result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
18
+ const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
46
19
  result.addError('', 'No params received');
47
20
  return [result];
48
21
  }
49
22
  return [true];
50
23
  };
51
24
  exports.shouldHaveParams = shouldHaveParams;
52
- var shouldHaveId = function (id) {
25
+ const shouldHaveId = (id) => {
53
26
  if (!id) {
54
- var result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
27
+ const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
55
28
  result.addError('', 'ID is required');
56
29
  return [result];
57
30
  }
58
31
  return [true];
59
32
  };
60
33
  exports.shouldHaveId = shouldHaveId;
61
- var validateList = function (_a) {
62
- var rules = _a.rules;
63
- // eslint-disable-next-line
64
- return function (args, opt) { return __awaiter(void 0, void 0, void 0, function () {
65
- var filter, result;
66
- return __generator(this, function (_a) {
67
- filter = (args || {}).filter;
68
- result = rules.validateSync(filter)[0];
69
- if (result) {
70
- return [2 /*return*/, [(0, checkItHelpers_1.createErrorOnCheckError)(result)]];
71
- }
72
- return [2 /*return*/, [true, {}]];
73
- });
74
- }); };
75
- };
34
+ const validateList = ({ rules }) =>
35
+ // eslint-disable-next-line
36
+ (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
37
+ const { filter } = args || {};
38
+ const [result] = rules.validateSync(filter);
39
+ if (result) {
40
+ return [(0, checkItHelpers_1.createErrorOnCheckError)(result)];
41
+ }
42
+ return [true, {}];
43
+ });
76
44
  exports.validateList = validateList;
77
- var validateCreate = function (_a) {
78
- var rules = _a.rules;
79
- // eslint-disable-next-line
80
- return function (args, opt) { return __awaiter(void 0, void 0, void 0, function () {
81
- var params, paramsCheck, result;
82
- return __generator(this, function (_a) {
83
- params = (args || {}).params;
84
- paramsCheck = (0, exports.shouldHaveParams)(params)[0];
85
- if (paramsCheck !== true) {
86
- return [2 /*return*/, [paramsCheck, {}]];
87
- }
88
- result = rules.validateSync(params)[0];
89
- if (result) {
90
- return [2 /*return*/, [(0, checkItHelpers_1.createErrorOnCheckError)(result), {}]];
91
- }
92
- return [2 /*return*/, [true, {}]];
93
- });
94
- }); };
95
- };
45
+ const validateCreate = ({ rules }) =>
46
+ // eslint-disable-next-line
47
+ (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
48
+ const { params } = args || {};
49
+ const [paramsCheck] = (0, exports.shouldHaveParams)(params);
50
+ if (paramsCheck !== true) {
51
+ return [paramsCheck, {}];
52
+ }
53
+ const [result] = rules.validateSync(params);
54
+ if (result) {
55
+ return [(0, checkItHelpers_1.createErrorOnCheckError)(result), {}];
56
+ }
57
+ return [true, {}];
58
+ });
96
59
  exports.validateCreate = validateCreate;
97
- var validateUpdate = function (_a) {
98
- var rules = _a.rules;
99
- // eslint-disable-next-line
100
- return function (args, opt) { return __awaiter(void 0, void 0, void 0, function () {
101
- var _a, where, params, idCheck, paramsCheck, result;
102
- return __generator(this, function (_b) {
103
- _a = args || {}, where = _a.where, params = _a.params;
104
- idCheck = (0, exports.shouldHaveParams)(where)[0];
105
- if (idCheck !== true) {
106
- return [2 /*return*/, [idCheck, {}]];
107
- }
108
- paramsCheck = (0, exports.shouldHaveParams)(params)[0];
109
- if (paramsCheck !== true) {
110
- return [2 /*return*/, [paramsCheck, {}]];
111
- }
112
- result = rules.validateSync(params)[0];
113
- if (result) {
114
- return [2 /*return*/, [(0, checkItHelpers_1.createErrorOnCheckError)(result), {}]];
115
- }
116
- return [2 /*return*/, [true, {}]];
117
- });
118
- }); };
119
- };
60
+ const validateUpdate = ({ rules }) =>
61
+ // eslint-disable-next-line
62
+ (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
63
+ const { where, params } = args || {};
64
+ const [idCheck] = (0, exports.shouldHaveParams)(where);
65
+ if (idCheck !== true) {
66
+ return [idCheck, {}];
67
+ }
68
+ const [paramsCheck] = (0, exports.shouldHaveParams)(params);
69
+ if (paramsCheck !== true) {
70
+ return [paramsCheck, {}];
71
+ }
72
+ const [result] = rules.validateSync(params);
73
+ if (result) {
74
+ return [(0, checkItHelpers_1.createErrorOnCheckError)(result), {}];
75
+ }
76
+ return [true, {}];
77
+ });
120
78
  exports.validateUpdate = validateUpdate;
@@ -1,35 +1,24 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  exports.buildConfig = void 0;
15
- var lodash_1 = require("lodash");
16
- var path_1 = require("path");
17
- var dotenv_safe_1 = require("dotenv-safe");
18
- var buildConfig = function (dirName, opt) {
19
- var opt2use = opt || {};
4
+ const lodash_1 = require("lodash");
5
+ const path_1 = require("path");
6
+ const dotenv_safe_1 = require("dotenv-safe");
7
+ const buildConfig = (dirName, opt) => {
8
+ const opt2use = opt || {};
20
9
  (0, dotenv_safe_1.config)({
21
10
  path: (0, path_1.resolve)(dirName, opt2use.envFile || '.env'),
22
11
  allowEmptyValues: opt2use.allowEmptyValues != null ? opt2use.allowEmptyValues : true,
23
12
  example: (0, path_1.join)(dirName, opt2use.envFileExample || '.env.example'),
24
13
  });
25
- var env = Object.assign({ NODE_ENV: opt2use.defaultNodeEnv || 'development' }, process.env);
14
+ const env = Object.assign({ NODE_ENV: opt2use.defaultNodeEnv || 'development' }, process.env);
26
15
  /**
27
16
  * Creates an application settings consisting of environment variables
28
17
  */
29
- var envVars = Object.keys(env).reduce(function (acc, key) {
18
+ const envVars = Object.keys(env).reduce((acc, key) => {
30
19
  acc[(0, lodash_1.camelCase)(key)] = env[key];
31
20
  return acc;
32
21
  }, {});
33
- return __assign(__assign({}, envVars), { nodeEnv: env.NODE_ENV, isProduction: env.NODE_ENV === 'production' });
22
+ return Object.assign(Object.assign({}, envVars), { nodeEnv: env.NODE_ENV, isProduction: env.NODE_ENV === 'production' });
34
23
  };
35
24
  exports.buildConfig = buildConfig;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HEADERS = exports.FIELDS = exports.ID_FIELD = void 0;
4
- var FIELDS = {
4
+ const FIELDS = {
5
5
  ID: 'id',
6
6
  STATUS: 'status',
7
7
  VERSION: 'version',
@@ -25,7 +25,7 @@ var FIELDS = {
25
25
  PHONE: 'phone',
26
26
  };
27
27
  exports.FIELDS = FIELDS;
28
- var HEADERS = {
28
+ const HEADERS = {
29
29
  AUTHORIZATION: 'authorization',
30
30
  SPACE_ID: 'x-space-id',
31
31
  API_KEY: 'x-api-key',
@@ -40,5 +40,5 @@ var HEADERS = {
40
40
  REQUESTED_LANGUAGE: 'x-lang',
41
41
  };
42
42
  exports.HEADERS = HEADERS;
43
- var ID_FIELD = FIELDS.ID;
43
+ const ID_FIELD = FIELDS.ID;
44
44
  exports.ID_FIELD = ID_FIELD;
@@ -8,46 +8,33 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- 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;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
39
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
13
  };
41
14
  Object.defineProperty(exports, "__esModule", { value: true });
42
15
  exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = void 0;
43
- var bluebird_1 = __importDefault(require("bluebird"));
44
- var lodash_1 = require("lodash");
45
- var SQLS = {
16
+ const bluebird_1 = __importDefault(require("bluebird"));
17
+ const lodash_1 = require("lodash");
18
+ const SQLS = {
46
19
  pg: {
47
- 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 "); },
48
- listTables: function () { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n "; },
49
- 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 "); },
50
- dropTables: function () { return "\n SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES';\n "; },
20
+ listTablesSchema: (appSettings) => `
21
+ SELECT TABLE_NAME as table_name
22
+ FROM INFORMATION_SCHEMA.TABLES
23
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
24
+ `,
25
+ listTables: () => `
26
+ SELECT TABLE_NAME as table_name
27
+ FROM INFORMATION_SCHEMA.TABLES
28
+ `,
29
+ dropTablesSchema: (appSettings) => `
30
+ SELECT 'DROP TABLE IF EXISTS ${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}.' || TABLE_NAME || ';' as cmd
31
+ FROM INFORMATION_SCHEMA.TABLES
32
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
33
+ `,
34
+ dropTables: () => `
35
+ SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd
36
+ FROM INFORMATION_SCHEMA.TABLES';
37
+ `,
51
38
  },
52
39
  };
53
40
  /**
@@ -58,28 +45,19 @@ var SQLS = {
58
45
  * @param knexHandle Knex handle object with configured connection to DB
59
46
  * @param appSettings settings with db related information
60
47
  */
61
- var dbCleanTable = function (table, knexHandle, appSettings) { return __awaiter(void 0, void 0, void 0, function () {
62
- var query, cleanTableFilters;
48
+ const dbCleanTable = (table, knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
63
49
  var _a;
64
- return __generator(this, function (_b) {
65
- switch (_b.label) {
66
- case 0:
67
- query = knexHandle(table).withSchema(appSettings.dbSchema).delete();
68
- cleanTableFilters = (_a = appSettings === null || appSettings === void 0 ? void 0 : appSettings.cleanTableFilters) === null || _a === void 0 ? void 0 : _a[table];
69
- if (cleanTableFilters != undefined) {
70
- if (Array.isArray(cleanTableFilters.where)) {
71
- cleanTableFilters.where.forEach(function (whereItem) {
72
- query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
73
- });
74
- }
75
- }
76
- return [4 /*yield*/, query];
77
- case 1:
78
- _b.sent();
79
- return [2 /*return*/];
50
+ const query = knexHandle(table).withSchema(appSettings.dbSchema).delete();
51
+ const cleanTableFilters = (_a = appSettings === null || appSettings === void 0 ? void 0 : appSettings.cleanTableFilters) === null || _a === void 0 ? void 0 : _a[table];
52
+ if (cleanTableFilters != undefined) {
53
+ if (Array.isArray(cleanTableFilters.where)) {
54
+ cleanTableFilters.where.forEach((whereItem) => {
55
+ query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
56
+ });
80
57
  }
81
- });
82
- }); };
58
+ }
59
+ yield query;
60
+ });
83
61
  exports.dbCleanTable = dbCleanTable;
84
62
  /**
85
63
  * Returns a list of tables in db schedm specified in settings
@@ -87,25 +65,17 @@ exports.dbCleanTable = dbCleanTable;
87
65
  * @param appSettings settings with db related information
88
66
  * @returns arrays of table names in the provided db schema
89
67
  */
90
- var dbListTables = function (knexHandle, appSettings) { return __awaiter(void 0, void 0, void 0, function () {
91
- var skipTables, query, tables;
92
- return __generator(this, function (_a) {
93
- switch (_a.label) {
94
- case 0:
95
- skipTables = (appSettings || {}).skipTables || [];
96
- query = SQLS[appSettings.dbType].listTablesSchema(appSettings);
97
- if (!appSettings.dbSchema) {
98
- query = SQLS[appSettings.dbType].listTables(appSettings);
99
- }
100
- return [4 /*yield*/, knexHandle.raw(query)];
101
- case 1:
102
- tables = _a.sent();
103
- return [2 /*return*/, (tables.rows || [])
104
- .map(function (row) { return row.table_name; })
105
- .filter(function (table) { return skipTables.indexOf(table) === -1; })];
106
- }
107
- });
108
- }); };
68
+ const dbListTables = (knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
69
+ const skipTables = (appSettings || {}).skipTables || [];
70
+ let query = SQLS[appSettings.dbType].listTablesSchema(appSettings);
71
+ if (!appSettings.dbSchema) {
72
+ query = SQLS[appSettings.dbType].listTables(appSettings);
73
+ }
74
+ const tables = yield knexHandle.raw(query);
75
+ return (tables.rows || [])
76
+ .map((row) => row.table_name)
77
+ .filter((table) => skipTables.indexOf(table) === -1);
78
+ });
109
79
  exports.dbListTables = dbListTables;
110
80
  /**
111
81
  * Removes all the records from provided list of tables
@@ -114,52 +84,38 @@ exports.dbListTables = dbListTables;
114
84
  * @param appSettings settings with db related information
115
85
  * @returns promise
116
86
  */
117
- var dbClean = function (tablesToClean, knexHandle, appSettings) { return __awaiter(void 0, void 0, void 0, function () {
118
- var idx, len;
119
- return __generator(this, function (_a) {
120
- switch (_a.label) {
121
- case 0:
122
- idx = 0, len = tablesToClean.length;
123
- _a.label = 1;
124
- case 1:
125
- if (!(idx < len)) return [3 /*break*/, 4];
126
- return [4 /*yield*/, dbCleanTable(tablesToClean[idx], knexHandle, appSettings)];
127
- case 2:
128
- _a.sent();
129
- _a.label = 3;
130
- case 3:
131
- ++idx;
132
- return [3 /*break*/, 1];
133
- case 4: return [2 /*return*/, new bluebird_1.default(function (resolve) {
134
- resolve(tablesToClean);
135
- })];
136
- }
87
+ const dbClean = (tablesToClean, knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
88
+ for (let idx = 0, len = tablesToClean.length; idx < len; ++idx) {
89
+ yield dbCleanTable(tablesToClean[idx], knexHandle, appSettings);
90
+ }
91
+ return new bluebird_1.default((resolve) => {
92
+ resolve(tablesToClean);
137
93
  });
138
- }); };
94
+ });
139
95
  exports.dbClean = dbClean;
140
96
  /**
141
97
  * Selects all the tables in the schema and drops them.
142
98
  * This approach does not work in case we have constraints.
143
99
  * TODO: Remove all constraints and then drop tables.
144
100
  */
145
- var dbWipe = function (knexHandle, appSettings) {
146
- var query = SQLS[appSettings.dbType].dropTablesSchema(appSettings);
101
+ const dbWipe = (knexHandle, appSettings) => {
102
+ let query = SQLS[appSettings.dbType].dropTablesSchema(appSettings);
147
103
  if (!appSettings.dbSchema) {
148
104
  query = SQLS[appSettings.dbType].dropTables(appSettings);
149
105
  }
150
106
  return knexHandle
151
107
  .raw(query)
152
- .then(function (result) { return result.rows.map(function (r) { return r.cmd; }); })
153
- .then(function (commands) { return bluebird_1.default.each(commands, function (cmd) { return knexHandle.raw(cmd); }); });
108
+ .then((result) => result.rows.map((r) => r.cmd))
109
+ .then((commands) => bluebird_1.default.each(commands, (cmd) => knexHandle.raw(cmd)));
154
110
  };
155
111
  exports.dbWipe = dbWipe;
156
112
  /**
157
113
  * Drop all tables, run migrations, then seed
158
114
  */
159
- var dbReset = function (knexHandle, appSettings) {
115
+ const dbReset = (knexHandle, appSettings) => {
160
116
  return dbWipe(knexHandle, appSettings)
161
- .then(function () { return dbRunMigrations(knexHandle, appSettings); })
162
- .catch(function (error) { return console.log('An exception has occurred on resetting database: ', error); });
117
+ .then(() => dbRunMigrations(knexHandle, appSettings))
118
+ .catch((error) => console.log('An exception has occurred on resetting database: ', error));
163
119
  };
164
120
  exports.dbReset = dbReset;
165
121
  /**
@@ -168,33 +124,23 @@ exports.dbReset = dbReset;
168
124
  * ie from [{table1: [], table2: [] }, { table3: [] }]
169
125
  * to { table1: [], table2: [], table3: []}
170
126
  */
171
- var dbTransformSeedsToObject = function (generatedSeedArrays) {
172
- return (0, lodash_1.reduce)(generatedSeedArrays, function (acc, cur) {
173
- for (var key in cur) {
174
- acc[key] = cur[key];
175
- }
176
- return acc;
177
- }, {});
178
- };
127
+ const dbTransformSeedsToObject = (generatedSeedArrays) => (0, lodash_1.reduce)(generatedSeedArrays, (acc, cur) => {
128
+ for (const key in cur) {
129
+ acc[key] = cur[key];
130
+ }
131
+ return acc;
132
+ }, {});
179
133
  exports.dbTransformSeedsToObject = dbTransformSeedsToObject;
180
- var dbRunMigrations = function (knexHandle, appSettings) {
134
+ const dbRunMigrations = (knexHandle, appSettings) => {
181
135
  return knexHandle.migrate
182
136
  .latest()
183
- .then(function (result) { return __awaiter(void 0, void 0, void 0, function () {
184
- return __generator(this, function (_a) {
185
- switch (_a.label) {
186
- case 0:
187
- if (!(appSettings && appSettings.runDbSeed && result[1].length > 0)) return [3 /*break*/, 2];
188
- return [4 /*yield*/, knexHandle.seed.run()];
189
- case 1:
190
- _a.sent();
191
- _a.label = 2;
192
- case 2:
193
- console.log('Ran', result[1].length, 'migration(s)');
194
- return [2 /*return*/, knexHandle.migrate.currentVersion()];
195
- }
196
- });
197
- }); })
198
- .then(function (version) { return console.log('Current version of database: ', version); });
137
+ .then((result) => __awaiter(void 0, void 0, void 0, function* () {
138
+ if (appSettings && appSettings.runDbSeed && result[1].length > 0) {
139
+ yield knexHandle.seed.run();
140
+ }
141
+ console.log('Ran', result[1].length, 'migration(s)');
142
+ return knexHandle.migrate.currentVersion();
143
+ }))
144
+ .then((version) => console.log('Current version of database: ', version));
199
145
  };
200
146
  exports.dbRunMigrations = dbRunMigrations;
package/build/dbSeeder.js CHANGED
@@ -31,104 +31,52 @@ 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.dbSeed = void 0;
66
- var path_1 = __importDefault(require("path"));
67
- var lodash_1 = require("lodash");
68
- var dbHelpers_1 = require("./dbHelpers");
69
- var generateSeeds = function (dirname, seedFiles) { return __awaiter(void 0, void 0, void 0, function () {
70
- var seedGroups, seedFileNames, seedFnExports, seedFns, seedFnsMap, i, seedFileName;
71
- return __generator(this, function (_a) {
72
- switch (_a.label) {
73
- case 0:
74
- seedGroups = [];
75
- seedFileNames = (0, lodash_1.flatten)(seedFiles);
76
- 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")))); }); }))];
77
- case 1:
78
- seedFnExports = _a.sent();
79
- seedFns = (0, lodash_1.map)(seedFnExports, 'default');
80
- seedFnsMap = {};
81
- for (i = 0; i < seedFileNames.length; i++) {
82
- seedFileName = seedFileNames[i];
83
- seedFnsMap[seedFileName] = seedFns[i];
84
- }
85
- seedFiles.reduce(function (seeds, fileGroup) {
86
- seedGroups = seedGroups.concat(fileGroup.reduce(function (group, filename) {
87
- var _a;
88
- var seedFn = seedFnsMap[filename];
89
- var seed = seedFn(seeds);
90
- var filenameCamel = (0, lodash_1.camelCase)(filename);
91
- seeds[filenameCamel] = seed;
92
- return Object.assign((_a = {}, _a[filenameCamel] = seed, _a), group);
93
- }, {}));
94
- return seeds;
95
- }, {});
96
- return [2 /*return*/, seedGroups];
97
- }
98
- });
99
- }); };
100
- var removeSeedsFromDb = function (seedFiles, knexHandle, config) {
101
- var tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
39
+ const path_1 = __importDefault(require("path"));
40
+ const lodash_1 = require("lodash");
41
+ const dbHelpers_1 = require("./dbHelpers");
42
+ const generateSeeds = (dirname, seedFiles) => __awaiter(void 0, void 0, void 0, function* () {
43
+ let seedGroups = [];
44
+ const seedFileNames = (0, lodash_1.flatten)(seedFiles);
45
+ const seedFnExports = yield Promise.all((0, lodash_1.map)(seedFileNames, (filename) => Promise.resolve().then(() => __importStar(require(path_1.default.join(dirname, `./objects/${filename}.js`))))));
46
+ const seedFns = (0, lodash_1.map)(seedFnExports, 'default');
47
+ const seedFnsMap = {};
48
+ for (let i = 0; i < seedFileNames.length; i++) {
49
+ const seedFileName = seedFileNames[i];
50
+ seedFnsMap[seedFileName] = seedFns[i];
51
+ }
52
+ seedFiles.reduce((seeds, fileGroup) => {
53
+ seedGroups = seedGroups.concat(fileGroup.reduce((group, filename) => {
54
+ const seedFn = seedFnsMap[filename];
55
+ const seed = seedFn(seeds);
56
+ const filenameCamel = (0, lodash_1.camelCase)(filename);
57
+ seeds[filenameCamel] = seed;
58
+ return Object.assign({ [filenameCamel]: seed }, group);
59
+ }, {}));
60
+ return seeds;
61
+ }, {});
62
+ return seedGroups;
63
+ });
64
+ const removeSeedsFromDb = (seedFiles, knexHandle, config) => {
65
+ const tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
102
66
  console.log('Deleting records from tables: ', tablesToReset);
103
67
  return (0, dbHelpers_1.dbClean)(tablesToReset, knexHandle, config);
104
68
  };
105
- var insertRecords = function (seedGroups, knexHandle, config) {
106
- var dbSchema = (config || {}).dbSchema;
69
+ const insertRecords = (seedGroups, knexHandle, config) => {
70
+ const { dbSchema } = config || {};
107
71
  console.log('Inserting seeds records tables tables...');
108
- return seedGroups.reduce(function (previousGroup, group) { return __awaiter(void 0, void 0, void 0, function () {
109
- return __generator(this, function (_a) {
110
- switch (_a.label) {
111
- case 0: return [4 /*yield*/, previousGroup];
112
- case 1:
113
- _a.sent();
114
- return [2 /*return*/, Promise.all(Object.keys(group).map(function (table) { return knexHandle(table).withSchema(dbSchema).insert(group[table]); }))];
115
- }
116
- });
117
- }); }, Promise.resolve());
72
+ return seedGroups.reduce((previousGroup, group) => __awaiter(void 0, void 0, void 0, function* () {
73
+ yield previousGroup;
74
+ return Promise.all(Object.keys(group).map((table) => knexHandle(table).withSchema(dbSchema).insert(group[table])));
75
+ }), Promise.resolve());
118
76
  };
119
- var dbSeed = function (dirname, seedFiles, knexHandle, config) { return __awaiter(void 0, void 0, void 0, function () {
120
- var groups;
121
- return __generator(this, function (_a) {
122
- switch (_a.label) {
123
- case 0: return [4 /*yield*/, generateSeeds(dirname, seedFiles)];
124
- case 1:
125
- groups = _a.sent();
126
- return [4 /*yield*/, removeSeedsFromDb(seedFiles, knexHandle, config)];
127
- case 2:
128
- _a.sent();
129
- return [4 /*yield*/, insertRecords(groups, knexHandle, config)];
130
- case 3: return [2 /*return*/, _a.sent()];
131
- }
132
- });
133
- }); };
77
+ const dbSeed = (dirname, seedFiles, knexHandle, config) => __awaiter(void 0, void 0, void 0, function* () {
78
+ const groups = yield generateSeeds(dirname, seedFiles);
79
+ yield removeSeedsFromDb(seedFiles, knexHandle, config);
80
+ return yield insertRecords(groups, knexHandle, config);
81
+ });
134
82
  exports.dbSeed = dbSeed;