@sdflc/backend-helpers 1.0.22 → 1.0.25

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.
@@ -7,8 +7,9 @@ exports.buildDefaultGatewayProps = void 0;
7
7
  var uuid_1 = require("uuid");
8
8
  var dayjs_1 = __importDefault(require("dayjs"));
9
9
  var lodash_1 = require("lodash");
10
+ var utils_1 = require("@sdflc/utils");
10
11
  var constants_1 = __importDefault(require("./constants"));
11
- var FIELDS = constants_1.default.FIELDS, STATUSES = constants_1.default.STATUSES;
12
+ var FIELDS = constants_1.default.FIELDS;
12
13
  var buildDefaultGatewayProps = function (args) {
13
14
  var config = args.config, tableName = args.tableName, filter = args.filter, updateFilter = args.updateFilter, hasStatus = args.hasStatus, hasRemovedAt = args.hasRemovedAt, hasRemovedAtStr = args.hasRemovedAtStr, setFields = args.setFields, idField = args.idField, activeStatuses = args.activeStatuses, redisClient = args.redisClient, context = args.context, buildKey = args.buildKey, returnFields = args.returnFields;
14
15
  return {
@@ -35,7 +36,7 @@ var buildDefaultGatewayProps = function (args) {
35
36
  cacheTtl: config.cacheTtl,
36
37
  noCache: false,
37
38
  idGenerator: function () {
38
- var id = uuid_1.v4();
39
+ var id = (0, uuid_1.v4)();
39
40
  return id;
40
41
  },
41
42
  insertFormatter: function (args) {
@@ -47,14 +48,14 @@ var buildDefaultGatewayProps = function (args) {
47
48
  updateFilter: function (query, params) {
48
49
  var id = (params || {}).id;
49
50
  if (id) {
50
- query.whereIn(FIELDS.ID, lodash_1.castArray(id));
51
+ query.whereIn(FIELDS.ID, (0, lodash_1.castArray)(id));
51
52
  }
52
53
  if (typeof updateFilter === 'function') {
53
54
  updateFilter(query, params);
54
55
  }
55
56
  },
56
57
  removeFormatter: function () {
57
- var removalTime = dayjs_1.default();
58
+ var removalTime = (0, dayjs_1.default)();
58
59
  var removedAt = removalTime.toDate();
59
60
  var obj = {
60
61
  removedAt: removedAt,
@@ -63,7 +64,7 @@ var buildDefaultGatewayProps = function (args) {
63
64
  obj[FIELDS.REMOVED_AT_STR] = removalTime.format('YYYYMMDDTHHmmssZ');
64
65
  }
65
66
  if (hasStatus === undefined || hasStatus === true) {
66
- obj[FIELDS.STATUS] = STATUSES.REMOVED;
67
+ obj[FIELDS.STATUS] = utils_1.STATUSES.REMOVED;
67
68
  }
68
69
  return obj;
69
70
  },
@@ -77,7 +78,7 @@ var buildDefaultGatewayProps = function (args) {
77
78
  }
78
79
  query = query.whereIn(FIELDS.ID, arr.map(function (item) { return item[FIELDS.ID]; }));
79
80
  if (hasStatus === undefined || hasStatus === true) {
80
- query.where(FIELDS.STATUS, '!=', STATUSES.REMOVED);
81
+ query.where(FIELDS.STATUS, '!=', utils_1.STATUSES.REMOVED);
81
82
  }
82
83
  },
83
84
  returnFields: returnFields || [FIELDS.ID],
@@ -11,7 +11,7 @@ var checkArray = function (arr, validator, prefix) {
11
11
  var itemResult = validator.validateSync(item)[0];
12
12
  if (itemResult) {
13
13
  Object.keys(itemResult.errors).forEach(function (key) {
14
- result.addError((prefix || '') + "[" + idx + "]." + key, itemResult.errors[key].message);
14
+ result.addError("".concat(prefix || '', "[").concat(idx, "].").concat(key), itemResult.errors[key].message);
15
15
  });
16
16
  }
17
17
  });
@@ -17,17 +17,17 @@ var path_1 = require("path");
17
17
  var dotenv_safe_1 = require("dotenv-safe");
18
18
  var buildConfig = function (dirName, opt) {
19
19
  var opt2use = opt || {};
20
- dotenv_safe_1.config({
21
- path: path_1.resolve(dirName, opt2use.envFile || '.env'),
20
+ (0, dotenv_safe_1.config)({
21
+ path: (0, path_1.resolve)(dirName, opt2use.envFile || '.env'),
22
22
  allowEmptyValues: opt2use.allowEmptyValues != null ? opt2use.allowEmptyValues : true,
23
- example: path_1.join(dirName, opt2use.envFileExample || '.env.example'),
23
+ example: (0, path_1.join)(dirName, opt2use.envFileExample || '.env.example'),
24
24
  });
25
25
  var env = Object.assign({ NODE_ENV: opt2use.defaultNodeEnv || 'development' }, process.env);
26
26
  /**
27
27
  * Creates an application settings consisting of environment variables
28
28
  */
29
29
  var envVars = Object.keys(env).reduce(function (acc, key) {
30
- acc[lodash_1.camelCase(key)] = env[key];
30
+ acc[(0, lodash_1.camelCase)(key)] = env[key];
31
31
  return acc;
32
32
  }, {});
33
33
  return __assign(__assign({}, envVars), { nodeEnv: env.NODE_ENV, isProduction: env.NODE_ENV === 'production' });
@@ -1,8 +1,5 @@
1
1
  declare const _default: {
2
- ID_FIELD: string;
2
+ ID_FIELD: any;
3
3
  FIELDS: any;
4
- STATUSES: any;
5
- ACCESS_RIGHTS: any;
6
- VALUE_TYPES: any;
7
4
  };
8
5
  export default _default;
@@ -1,6 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var ID_FIELD = 'id';
4
3
  var FIELDS = {
5
4
  ID: 'id',
6
5
  STATUS: 'status',
@@ -19,39 +18,8 @@ var FIELDS = {
19
18
  ORDER_NO: 'order_no',
20
19
  SPACE_ID: 'space_id',
21
20
  };
22
- var STATUSES = {
23
- TEST: 50,
24
- ACTIVE: 100,
25
- DRAFT: 200,
26
- PENDING: 300,
27
- BLOCKED: 1000,
28
- DISABLED: 5000,
29
- REMOVED: 10000,
30
- };
31
- var ACCESS_RIGHTS = {
32
- LIST: 1,
33
- GET: 2,
34
- CREATE: 4,
35
- UPDATE: 8,
36
- REMOVE: 16,
37
- RUN: 32,
38
- };
39
- var VALUE_TYPES = {
40
- NUMBER: 100,
41
- INTEGER: 101,
42
- FLOAT: 102,
43
- CURRENCY: 103,
44
- BOOLEAN: 200,
45
- STRING: 300,
46
- JSON: 400,
47
- EMAIL: 1001,
48
- PHONE: 1002,
49
- URL: 1003,
50
- };
21
+ var ID_FIELD = FIELDS.ID;
51
22
  exports.default = {
52
23
  ID_FIELD: ID_FIELD,
53
24
  FIELDS: FIELDS,
54
- STATUSES: STATUSES,
55
- ACCESS_RIGHTS: ACCESS_RIGHTS,
56
- VALUE_TYPES: VALUE_TYPES,
57
25
  };
@@ -60,7 +60,7 @@ var DataCache = /** @class */ (function () {
60
60
  this.config = props;
61
61
  this.buildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
62
62
  this.batchLoaderDefault = this.batchLoaderDefault.bind(this);
63
- this.redisDataLoader = redisClient ? redis_dataloader_1.default({ redis: redisClient }) : null;
63
+ this.redisDataLoader = redisClient ? (0, redis_dataloader_1.default)({ redis: redisClient }) : null;
64
64
  var fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(props);
65
65
  var prefixToUse = (context === null || context === void 0 ? void 0 : context.keyPrefix) || keyPrefix;
66
66
  this.init(fn, prefixToUse, context);
package/build/database.js CHANGED
@@ -51,7 +51,7 @@ var Database = /** @class */ (function () {
51
51
  if (!props.knexConfig) {
52
52
  throw new Error('The Database class expects to have `knexConfig` in its constructor props');
53
53
  }
54
- this.knexHandle = knex_1.default(props.knexConfig);
54
+ this.knexHandle = (0, knex_1.default)(props.knexConfig);
55
55
  this.dbSchema = props.dbSchema || '';
56
56
  this.trx = props.trx;
57
57
  }
@@ -187,7 +187,7 @@ var Database = /** @class */ (function () {
187
187
  if (mapBy) {
188
188
  fnBuildKey_1 = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
189
189
  dbResults = dbResults.reduce(function (acc, item) {
190
- var key = fnBuildKey_1(item[lodash_1.camelCase(mapBy)]);
190
+ var key = fnBuildKey_1(item[(0, lodash_1.camelCase)(mapBy)]);
191
191
  if (Array.isArray(calculated) && calculated.length > 0) {
192
192
  _this.doCalculated(item, calculated);
193
193
  }
@@ -44,9 +44,9 @@ var bluebird_1 = __importDefault(require("bluebird"));
44
44
  var lodash_1 = require("lodash");
45
45
  var SQLS = {
46
46
  pg: {
47
- listTablesSchema: function (appSettings) { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + "';\n "; },
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
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 " + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + ".' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + "';\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
50
  dropTables: function () { return "\n SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES';\n "; },
51
51
  },
52
52
  };
@@ -169,7 +169,7 @@ exports.dbReset = dbReset;
169
169
  * to { table1: [], table2: [], table3: []}
170
170
  */
171
171
  var dbTransformSeedsToObject = function (generatedSeedArrays) {
172
- return lodash_1.reduce(generatedSeedArrays, function (acc, cur) {
172
+ return (0, lodash_1.reduce)(generatedSeedArrays, function (acc, cur) {
173
173
  for (var key in cur) {
174
174
  acc[key] = cur[key];
175
175
  }
@@ -65,9 +65,9 @@ var lodash_1 = require("lodash");
65
65
  var utils_1 = require("@sdflc/utils");
66
66
  var SQLS = {
67
67
  pg: {
68
- listTablesSchema: function (appSettings) { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + "';\n "; },
68
+ 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 "); },
69
69
  listTables: function () { return "\n SELECT TABLE_NAME as table_name\n FROM INFORMATION_SCHEMA.TABLES\n "; },
70
- dropTablesSchema: function (appSettings) { return "\n SELECT 'DROP TABLE IF EXISTS " + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + ".' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = '" + (appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema) + "';\n "; },
70
+ 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 "); },
71
71
  dropTables: function () { return "\n SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd\n FROM INFORMATION_SCHEMA.TABLES';\n "; },
72
72
  },
73
73
  };
@@ -91,9 +91,9 @@ var DbMigratorAndSeeder = /** @class */ (function () {
91
91
  _a.sent();
92
92
  _a.label = 3;
93
93
  case 3:
94
- this.logger.log("Ran " + result[1].length + " migration(s)");
94
+ this.logger.log("Ran ".concat(result[1].length, " migration(s)"));
95
95
  version = this.knexHandle.migrate.currentVersion();
96
- this.logger.log("Current version of database: " + version);
96
+ this.logger.log("Current version of database: ".concat(version));
97
97
  return [2 /*return*/];
98
98
  }
99
99
  });
@@ -106,7 +106,7 @@ var DbMigratorAndSeeder = /** @class */ (function () {
106
106
  * to { table1: [], table2: [], table3: []}
107
107
  */
108
108
  DbMigratorAndSeeder.prototype.transformSeedsToObject = function (generatedSeedArrays) {
109
- return lodash_1.reduce(generatedSeedArrays, function (acc, cur) {
109
+ return (0, lodash_1.reduce)(generatedSeedArrays, function (acc, cur) {
110
110
  for (var key in cur) {
111
111
  acc[key] = cur[key];
112
112
  }
@@ -259,11 +259,11 @@ var DbMigratorAndSeeder = /** @class */ (function () {
259
259
  switch (_a.label) {
260
260
  case 0:
261
261
  seedGroups = [];
262
- seedFileNames = lodash_1.flatten(seedFiles);
263
- return [4 /*yield*/, Promise.all(lodash_1.map(seedFileNames, function (filename) { return Promise.resolve().then(function () { return __importStar(require(path_1.default.join(dirname, "./objects/" + filename + ".js"))); }); }))];
262
+ seedFileNames = (0, lodash_1.flatten)(seedFiles);
263
+ 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")))); }); }))];
264
264
  case 1:
265
265
  seedFnExports = _a.sent();
266
- seedFns = lodash_1.map(seedFnExports, 'default');
266
+ seedFns = (0, lodash_1.map)(seedFnExports, 'default');
267
267
  seedFnsMap = {};
268
268
  for (i = 0; i < seedFileNames.length; i++) {
269
269
  seedFileName = seedFileNames[i];
@@ -274,7 +274,7 @@ var DbMigratorAndSeeder = /** @class */ (function () {
274
274
  var _a;
275
275
  var seedFn = seedFnsMap[filename];
276
276
  var seed = seedFn(seeds);
277
- var filenameCamel = lodash_1.camelCase(filename);
277
+ var filenameCamel = (0, lodash_1.camelCase)(filename);
278
278
  seeds[filenameCamel] = seed;
279
279
  return Object.assign((_a = {}, _a[filenameCamel] = seed, _a), group);
280
280
  }, {}));
@@ -286,7 +286,7 @@ var DbMigratorAndSeeder = /** @class */ (function () {
286
286
  });
287
287
  };
288
288
  DbMigratorAndSeeder.prototype.removeSeedsFromDb = function (seedFiles) {
289
- var tablesToReset = lodash_1.flatten(seedFiles).reverse();
289
+ var tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
290
290
  this.logger.log('Deleting records from tables: ', tablesToReset);
291
291
  return this.cleanDb(tablesToReset);
292
292
  };
package/build/dbSeeder.js CHANGED
@@ -68,11 +68,11 @@ var generateSeeds = function (dirname, seedFiles) { return __awaiter(void 0, voi
68
68
  switch (_a.label) {
69
69
  case 0:
70
70
  seedGroups = [];
71
- seedFileNames = lodash_1.flatten(seedFiles);
72
- return [4 /*yield*/, Promise.all(lodash_1.map(seedFileNames, function (filename) { return Promise.resolve().then(function () { return __importStar(require(path_1.default.join(dirname, "./objects/" + filename + ".js"))); }); }))];
71
+ seedFileNames = (0, lodash_1.flatten)(seedFiles);
72
+ 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")))); }); }))];
73
73
  case 1:
74
74
  seedFnExports = _a.sent();
75
- seedFns = lodash_1.map(seedFnExports, 'default');
75
+ seedFns = (0, lodash_1.map)(seedFnExports, 'default');
76
76
  seedFnsMap = {};
77
77
  for (i = 0; i < seedFileNames.length; i++) {
78
78
  seedFileName = seedFileNames[i];
@@ -83,7 +83,7 @@ var generateSeeds = function (dirname, seedFiles) { return __awaiter(void 0, voi
83
83
  var _a;
84
84
  var seedFn = seedFnsMap[filename];
85
85
  var seed = seedFn(seeds);
86
- var filenameCamel = lodash_1.camelCase(filename);
86
+ var filenameCamel = (0, lodash_1.camelCase)(filename);
87
87
  seeds[filenameCamel] = seed;
88
88
  return Object.assign((_a = {}, _a[filenameCamel] = seed, _a), group);
89
89
  }, {}));
@@ -94,9 +94,9 @@ var generateSeeds = function (dirname, seedFiles) { return __awaiter(void 0, voi
94
94
  });
95
95
  }); };
96
96
  var removeSeedsFromDb = function (seedFiles, knexHandle, config) {
97
- var tablesToReset = lodash_1.flatten(seedFiles).reverse();
97
+ var tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
98
98
  console.log('Deleting records from tables: ', tablesToReset);
99
- return dbHelpers_1.dbClean(tablesToReset, knexHandle, config);
99
+ return (0, dbHelpers_1.dbClean)(tablesToReset, knexHandle, config);
100
100
  };
101
101
  var insertRecords = function (seedGroups, knexHandle, config) {
102
102
  var dbSchema = (config || {}).dbSchema;
@@ -1,5 +1,5 @@
1
1
  import { DbFieldAddDefaultInterface } from './interfaces';
2
- declare const dbFieldAddDefaults: (table: any, opt?: DbFieldAddDefaultInterface | undefined) => void;
2
+ export declare const dbFieldAddDefaults: (table: any, opt?: DbFieldAddDefaultInterface | undefined) => void;
3
3
  export declare const addOrderNo: (table: any, opt?: any) => any;
4
4
  export declare const addAmount: (table: any, fieldName: string) => any;
5
5
  export declare const addSpaceId: (table: any, opt?: any) => any;
@@ -7,4 +7,3 @@ export declare const addUserId: (table: any, opt?: any) => any;
7
7
  export declare const defaultFields: (opt?: any) => {
8
8
  [x: number]: string;
9
9
  };
10
- export { dbFieldAddDefaults };
@@ -3,16 +3,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.dbFieldAddDefaults = exports.defaultFields = exports.addUserId = exports.addSpaceId = exports.addAmount = exports.addOrderNo = void 0;
7
- var constants_1 = __importDefault(require("./constants"));
6
+ exports.defaultFields = exports.addUserId = exports.addSpaceId = exports.addAmount = exports.addOrderNo = exports.dbFieldAddDefaults = void 0;
8
7
  var utils_1 = require("@sdflc/utils");
9
- var FIELDS = constants_1.default.FIELDS, STATUSES = constants_1.default.STATUSES;
8
+ var constants_1 = __importDefault(require("./constants"));
9
+ var FIELDS = constants_1.default.FIELDS;
10
10
  var dbFieldAddDefaults = function (table, opt) {
11
11
  var _a = opt || {}, addUserInfo = _a.addUserInfo, addVersion = _a.addVersion, addStatus = _a.addStatus, skipTimestamps = _a.skipTimestamps, skipRemovedAtStr = _a.skipRemovedAtStr;
12
12
  if (addStatus) {
13
13
  table
14
14
  .integer(FIELDS.STATUS)
15
- .defaultTo(STATUSES.ACTIVE)
15
+ .defaultTo(utils_1.STATUSES.ACTIVE)
16
16
  .comment('The field is used to specify record status: 50 - Test, 100 - Active, 200 - Draft, 300 - Pending, 1000 - Blocked, 5000 - Disabled, 10000 - Removed');
17
17
  }
18
18
  if (addVersion) {
@@ -57,7 +57,7 @@ exports.addAmount = addAmount;
57
57
  var addSpaceId = function (table, opt) {
58
58
  var chain = table.text(FIELDS.SPACE_ID).notNullable().comment('Reference to the space table');
59
59
  if ((opt === null || opt === void 0 ? void 0 : opt.addForeignKey) === true) {
60
- table.foreign(FIELDS.SPACE_ID).references("space." + FIELDS.ID).onUpdate('CASCADE').onDelete('CASCADE');
60
+ table.foreign(FIELDS.SPACE_ID).references("space.".concat(FIELDS.ID)).onUpdate('CASCADE').onDelete('CASCADE');
61
61
  }
62
62
  return chain;
63
63
  };
@@ -65,7 +65,7 @@ exports.addSpaceId = addSpaceId;
65
65
  var addUserId = function (table, opt) {
66
66
  var chain = table.uuid(FIELDS.USER_ID).notNullable().comment('Reference to the user table');
67
67
  if ((opt === null || opt === void 0 ? void 0 : opt.addForeignKey) === true) {
68
- table.foreign(FIELDS.userId).references("user." + FIELDS.ID).onUpdate('CASCADE').onDelete('CASCADE');
68
+ table.foreign(FIELDS.userId).references("user.".concat(FIELDS.ID)).onUpdate('CASCADE').onDelete('CASCADE');
69
69
  }
70
70
  return chain;
71
71
  };
package/build/index.d.ts CHANGED
@@ -13,7 +13,7 @@ export { BaseGateway } from './baseGateway';
13
13
  export { BaseCore } from './baseCore';
14
14
  export { createApiContext, createContextDefault } from './apiContext';
15
15
  export { BaseController } from './baseController';
16
- export { dbFieldAddDefaults } from './dbTableHelpers';
16
+ export { dbFieldAddDefaults, addOrderNo, addAmount, addSpaceId, addUserId, defaultFields } from './dbTableHelpers';
17
17
  export { buildDefaultResolvers } from './resolversHelpers';
18
18
  export { createUserToken, verifyUserToken } from './userToken';
19
19
  export { constants };
package/build/index.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.checkPassword = exports.getSaltAndHash = exports.buildDefaultGatewayProps = exports.constants = exports.verifyUserToken = exports.createUserToken = exports.buildDefaultResolvers = exports.dbFieldAddDefaults = exports.BaseController = exports.createContextDefault = exports.createApiContext = exports.BaseCore = exports.BaseGateway = exports.DataCache = exports.createErrorOnCheckError = exports.checkArray = exports.createRedisClient = exports.buildKnexConfig = exports.dbSeed = exports.DbMigratorAndSeeder = exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.Database = exports.buildConfig = void 0;
6
+ exports.checkPassword = exports.getSaltAndHash = exports.buildDefaultGatewayProps = exports.constants = exports.verifyUserToken = exports.createUserToken = exports.buildDefaultResolvers = exports.defaultFields = exports.addUserId = exports.addSpaceId = exports.addAmount = exports.addOrderNo = exports.dbFieldAddDefaults = exports.BaseController = exports.createContextDefault = exports.createApiContext = exports.BaseCore = exports.BaseGateway = exports.DataCache = exports.createErrorOnCheckError = exports.checkArray = exports.createRedisClient = exports.buildKnexConfig = exports.dbSeed = exports.DbMigratorAndSeeder = exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.Database = exports.buildConfig = void 0;
7
7
  var constants_1 = __importDefault(require("./constants"));
8
8
  exports.constants = constants_1.default;
9
9
  var configBulder_1 = require("./configBulder");
@@ -42,6 +42,11 @@ var baseController_1 = require("./baseController");
42
42
  Object.defineProperty(exports, "BaseController", { enumerable: true, get: function () { return baseController_1.BaseController; } });
43
43
  var dbTableHelpers_1 = require("./dbTableHelpers");
44
44
  Object.defineProperty(exports, "dbFieldAddDefaults", { enumerable: true, get: function () { return dbTableHelpers_1.dbFieldAddDefaults; } });
45
+ Object.defineProperty(exports, "addOrderNo", { enumerable: true, get: function () { return dbTableHelpers_1.addOrderNo; } });
46
+ Object.defineProperty(exports, "addAmount", { enumerable: true, get: function () { return dbTableHelpers_1.addAmount; } });
47
+ Object.defineProperty(exports, "addSpaceId", { enumerable: true, get: function () { return dbTableHelpers_1.addSpaceId; } });
48
+ Object.defineProperty(exports, "addUserId", { enumerable: true, get: function () { return dbTableHelpers_1.addUserId; } });
49
+ Object.defineProperty(exports, "defaultFields", { enumerable: true, get: function () { return dbTableHelpers_1.defaultFields; } });
45
50
  var resolversHelpers_1 = require("./resolversHelpers");
46
51
  Object.defineProperty(exports, "buildDefaultResolvers", { enumerable: true, get: function () { return resolversHelpers_1.buildDefaultResolvers; } });
47
52
  var userToken_1 = require("./userToken");
@@ -4,10 +4,11 @@ import { Database } from '../database';
4
4
  import { BaseGateway } from '../baseGateway';
5
5
  import { BaseCoreValidatorsInterface } from './BaseCoreValidatorsInterface';
6
6
  import { BaseCoreDoingWhatInterface } from './BaseCoreDoingWhatInterface';
7
+ import { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
7
8
  export interface BaseCoreInterface {
8
9
  db: Database;
9
10
  context?: any;
10
- gateway?: BaseGateway;
11
+ gateway?: any;
11
12
  gateways?: any;
12
13
  isProduction: boolean;
13
14
  logLevel: LoggerLevels;
@@ -35,4 +36,8 @@ export interface BaseCoreInterface {
35
36
  onException?(params: any, opt?: BaseCoreActionsInterface): any;
36
37
  validators?: BaseCoreValidatorsInterface;
37
38
  authenticate?(params: any, opt?: BaseCoreActionsInterface): Promise<any[]> | any[];
39
+ gwSpace?: BaseGateway;
40
+ interserviceApiKey?: string;
41
+ jwtSecret?: string;
42
+ verifytokenArgs?: VerifyUserTokenArgs;
38
43
  }
@@ -5,7 +5,7 @@ import { LoaderInterface } from './LoaderInterface';
5
5
  import { SortItemInterface } from './SortItemInterface';
6
6
  export interface BaseGatewayInterface {
7
7
  db: Database;
8
- core: BaseCore;
8
+ core?: BaseCore;
9
9
  table?: string;
10
10
  idField?: string;
11
11
  setFields?: string[] | string;
@@ -1,7 +1,4 @@
1
- import { UserTokenParams } from './UserTokenParams';
2
1
  export interface CreateUserTokenArgs {
3
- params: UserTokenParams;
4
- secret: string;
5
2
  algorithm?: any;
6
3
  audience?: string | string[];
7
4
  issuer?: string;
@@ -1,6 +1,4 @@
1
1
  export interface VerifyUserTokenArgs {
2
- token: string;
3
- secret: string;
4
2
  algorithms?: any;
5
3
  audience?: string | string[];
6
4
  issuer?: string | string[];
@@ -26,14 +26,14 @@ var camelResponse = function (result) {
26
26
  if (!result || result.rows) {
27
27
  return result;
28
28
  }
29
- return utils_1.camelKeys(result);
29
+ return (0, utils_1.camelKeys)(result);
30
30
  };
31
31
  var buildKnexConfig = function (dirName, appConfig) {
32
32
  var dbType = appConfig.dbType, dbHost = appConfig.dbHost, dbPort = appConfig.dbPort, dbName = appConfig.dbName, dbSchema = appConfig.dbSchema, dbUser = appConfig.dbUser, dbPassword = appConfig.dbPassword, debug = appConfig.debug, nodeEnv = appConfig.nodeEnv, migrationsTemplateFileName = appConfig.migrationsTemplateFileName, migrationsFolder = appConfig.migrationsFolder, migrationsTable = appConfig.migrationsTable, useSchemaForMigrationsTable = appConfig.useSchemaForMigrationsTable, seedsFolder = appConfig.seedsFolder, seedsFolderDev = appConfig.seedsFolderDev, seedsFolderProd = appConfig.seedsFolderProd;
33
33
  var sharedConfig = {
34
34
  client: dbType || 'pg',
35
35
  postProcessResponse: camelResponse,
36
- wrapIdentifier: function (value, origImpl) { return (value === '*' ? origImpl(value) : origImpl(lodash_1.snakeCase(value))); },
36
+ wrapIdentifier: function (value, origImpl) { return (value === '*' ? origImpl(value) : origImpl((0, lodash_1.snakeCase)(value))); },
37
37
  connection: {
38
38
  host: dbHost,
39
39
  port: dbPort,
@@ -48,18 +48,18 @@ var buildKnexConfig = function (dirName, appConfig) {
48
48
  stub: path_1.default.join(dirName, migrationsTemplateFileName || defaultMigrationsTemplateFileName),
49
49
  directory: path_1.default.join(dirName, migrationsFolder || defaultMigrationsFolder),
50
50
  tableName: migrationsTable ||
51
- "" + (useSchemaForMigrationsTable ? dbSchema + "." : '') + (migrationsTable || defaultMigrationsTable),
51
+ "".concat(useSchemaForMigrationsTable ? "".concat(dbSchema, ".") : '').concat(migrationsTable || defaultMigrationsTable),
52
52
  }, seeds: {
53
53
  directory: path_1.default.join(dirName, seedsFolderDev || seedsFolder || defaultSeedsFolder),
54
54
  } }),
55
55
  production: __assign(__assign({}, sharedConfig), { debug: debug, migrations: {
56
56
  directory: path_1.default.join(dirName, migrationsFolder || defaultMigrationsFolder),
57
57
  tableName: migrationsTable ||
58
- "" + (useSchemaForMigrationsTable ? dbSchema + "." : '') + (migrationsTable || defaultMigrationsTable),
58
+ "".concat(useSchemaForMigrationsTable ? "".concat(dbSchema, ".") : '').concat(migrationsTable || defaultMigrationsTable),
59
59
  }, seeds: {
60
60
  directory: path_1.default.join(dirName, seedsFolderProd || seedsFolder || defaultSeedsFolder),
61
61
  } }),
62
62
  };
63
- return lodash_1.get(config, nodeEnv);
63
+ return (0, lodash_1.get)(config, nodeEnv);
64
64
  };
65
65
  exports.buildKnexConfig = buildKnexConfig;
@@ -17,56 +17,55 @@ var buildDefaultResolvers = function (args) {
17
17
  var Query = __assign({}, (query || {}));
18
18
  var Mutation = __assign({}, (mutation || {}));
19
19
  if (disableList !== true) {
20
- Query[prefix + "List"] = function (parent, args, context) {
20
+ Query["".concat(prefix, "List")] = function (parent, args, context) {
21
21
  return context[core].list(args);
22
22
  };
23
23
  }
24
24
  if (disableGet !== true) {
25
- Query[prefix + "Get"] = function (parent, args, context) {
25
+ Query["".concat(prefix, "Get")] = function (parent, args, context) {
26
26
  return context[core].get(args);
27
27
  };
28
28
  }
29
29
  if (disableGetMany !== true) {
30
- Query[prefix + "GetMany"] = function (parent, args, context) {
30
+ Query["".concat(prefix, "GetMany")] = function (parent, args, context) {
31
31
  return context[core].getMany(args);
32
32
  };
33
33
  }
34
34
  if (disableCreate !== true) {
35
- Mutation[prefix + "Create"] = function (parent, args, context) {
35
+ Mutation["".concat(prefix, "Create")] = function (parent, args, context) {
36
36
  return context[core].create(args);
37
37
  };
38
38
  }
39
39
  if (disableCreateMany !== true) {
40
- Mutation[prefix + "CreateMany"] = function (parent, args, context) {
40
+ Mutation["".concat(prefix, "CreateMany")] = function (parent, args, context) {
41
41
  return context[core].createMany(args);
42
42
  };
43
43
  }
44
44
  if (disableUpdate !== true) {
45
- Mutation[prefix + "Update"] = function (parent, args, context) {
45
+ Mutation["".concat(prefix, "Update")] = function (parent, args, context) {
46
46
  return context[core].update(args);
47
47
  };
48
48
  }
49
49
  if (disableUpdateMany !== true) {
50
- Mutation[prefix + "UpdateMany"] = function (parent, args, context) {
50
+ Mutation["".concat(prefix, "UpdateMany")] = function (parent, args, context) {
51
51
  return context[core].updateMany(args);
52
52
  };
53
53
  }
54
54
  if (disableSet !== true) {
55
- Mutation[prefix + "Set"] = function (parent, args, context) {
55
+ Mutation["".concat(prefix, "Set")] = function (parent, args, context) {
56
56
  return context[core].set(args);
57
57
  };
58
58
  }
59
59
  if (disableRemove !== true) {
60
- Mutation[prefix + "Remove"] = function (parent, args, context) {
60
+ Mutation["".concat(prefix, "Remove")] = function (parent, args, context) {
61
61
  return context[core].remove(args);
62
62
  };
63
63
  }
64
64
  if (disableRemoveMany !== true) {
65
- Mutation[prefix + "RemoveMany"] = function (parent, args, context) {
65
+ Mutation["".concat(prefix, "RemoveMany")] = function (parent, args, context) {
66
66
  return context[core].removeMany(args);
67
67
  };
68
68
  }
69
- return __assign({ Query: Query,
70
- Mutation: Mutation }, (types || {}));
69
+ return __assign({ Query: Query, Mutation: Mutation }, (types || {}));
71
70
  };
72
71
  exports.buildDefaultResolvers = buildDefaultResolvers;
@@ -1,4 +1,4 @@
1
1
  import { OpResult } from '@sdflc/api-helpers';
2
- import { CreateUserTokenArgs, VerifyUserTokenArgs } from './interfaces';
3
- export declare const createUserToken: (args: CreateUserTokenArgs) => OpResult;
4
- export declare const verifyUserToken: (args: VerifyUserTokenArgs) => OpResult;
2
+ import { UserTokenParams, CreateUserTokenArgs, VerifyUserTokenArgs } from './interfaces';
3
+ export declare const createUserToken: (params: UserTokenParams, secret: string, opt: CreateUserTokenArgs) => OpResult;
4
+ export declare const verifyUserToken: (token: string, secret: string, args?: VerifyUserTokenArgs | undefined) => OpResult;
@@ -6,13 +6,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.verifyUserToken = exports.createUserToken = void 0;
7
7
  var jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
8
  var api_helpers_1 = require("@sdflc/api-helpers");
9
- var createUserToken = function (args) {
10
- var _a = args || {}, params = _a.params, secret = _a.secret, algorithm = _a.algorithm, audience = _a.audience, issuer = _a.issuer, jwtid = _a.jwtid, subject = _a.subject, noTimestamp = _a.noTimestamp, header = _a.header, keyid = _a.keyid, expiresIn = _a.expiresIn;
11
- if (!args) {
9
+ var createUserToken = function (params, secret, opt) {
10
+ var _a = opt || {}, algorithm = _a.algorithm, audience = _a.audience, issuer = _a.issuer, jwtid = _a.jwtid, subject = _a.subject, noTimestamp = _a.noTimestamp, header = _a.header, keyid = _a.keyid, expiresIn = _a.expiresIn;
11
+ if (!params || !secret) {
12
12
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED);
13
13
  }
14
14
  var token = jsonwebtoken_1.default.sign(params, secret, {
15
- algorithm: algorithm,
15
+ algorithm: algorithm || 'HS256',
16
16
  audience: audience,
17
17
  issuer: issuer,
18
18
  jwtid: jwtid,
@@ -25,23 +25,28 @@ var createUserToken = function (args) {
25
25
  return api_helpers_1.OpResult.ok(token);
26
26
  };
27
27
  exports.createUserToken = createUserToken;
28
- var verifyUserToken = function (args) {
29
- var _a = args || {}, token = _a.token, secret = _a.secret, algorithms = _a.algorithms, audience = _a.audience, issuer = _a.issuer, ignoreExpiration = _a.ignoreExpiration, ignoreNotBefore = _a.ignoreNotBefore, subject = _a.subject, clockTolerance = _a.clockTolerance, maxAge = _a.maxAge, clockTimestamp = _a.clockTimestamp, nonce = _a.nonce;
28
+ var verifyUserToken = function (token, secret, args) {
29
+ var _a = args || {}, algorithms = _a.algorithms, audience = _a.audience, issuer = _a.issuer, ignoreExpiration = _a.ignoreExpiration, ignoreNotBefore = _a.ignoreNotBefore, subject = _a.subject, clockTolerance = _a.clockTolerance, maxAge = _a.maxAge, clockTimestamp = _a.clockTimestamp, nonce = _a.nonce;
30
30
  if (!args) {
31
31
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED);
32
32
  }
33
- var obj = jsonwebtoken_1.default.verify(token, secret, {
34
- algorithms: algorithms,
35
- audience: audience,
36
- issuer: issuer,
37
- ignoreExpiration: ignoreExpiration,
38
- ignoreNotBefore: ignoreNotBefore,
39
- subject: subject,
40
- clockTolerance: clockTolerance,
41
- maxAge: maxAge,
42
- clockTimestamp: clockTimestamp,
43
- nonce: nonce,
44
- });
45
- return api_helpers_1.OpResult.ok(obj);
33
+ try {
34
+ var obj = jsonwebtoken_1.default.verify(token, secret, {
35
+ algorithms: algorithms || ['HS256'],
36
+ audience: audience,
37
+ issuer: issuer,
38
+ ignoreExpiration: ignoreExpiration,
39
+ ignoreNotBefore: ignoreNotBefore,
40
+ subject: subject,
41
+ clockTolerance: clockTolerance,
42
+ maxAge: maxAge,
43
+ clockTimestamp: clockTimestamp,
44
+ nonce: nonce,
45
+ });
46
+ return api_helpers_1.OpResult.ok(obj);
47
+ }
48
+ catch (ex) {
49
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED);
50
+ }
46
51
  };
47
52
  exports.verifyUserToken = verifyUserToken;