@sdflc/backend-helpers 1.0.78 → 1.0.79

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 (109) hide show
  1. package/build/BaseCore.js +0 -3
  2. package/build/BaseGateway.js +0 -2
  3. package/build/RedisDataLoader.js +7 -12
  4. package/build/commonValidators.js +3 -9
  5. package/build/esm/BaseCore.d.ts +88 -0
  6. package/build/esm/BaseCore.js +810 -0
  7. package/build/esm/BaseGateway.d.ts +49 -0
  8. package/build/esm/BaseGateway.js +476 -0
  9. package/build/esm/DataCache.d.ts +14 -0
  10. package/build/esm/DataCache.js +98 -0
  11. package/build/esm/Database.d.ts +32 -0
  12. package/build/esm/Database.js +192 -0
  13. package/build/esm/DbMigratorAndSeeder.d.ts +49 -0
  14. package/build/esm/DbMigratorAndSeeder.js +199 -0
  15. package/build/esm/RedisDataLoader.d.ts +41 -0
  16. package/build/esm/RedisDataLoader.js +237 -0
  17. package/build/esm/apiContext.d.ts +11 -0
  18. package/build/esm/apiContext.js +135 -0
  19. package/build/esm/baseController.d.ts +17 -0
  20. package/build/esm/baseController.js +60 -0
  21. package/build/esm/checkItHelpers.d.ts +3 -0
  22. package/build/esm/checkItHelpers.js +23 -0
  23. package/build/esm/commonValidators.d.ts +17 -0
  24. package/build/esm/commonValidators.js +273 -0
  25. package/build/esm/configBulder.d.ts +2 -0
  26. package/build/esm/configBulder.js +28 -0
  27. package/build/esm/constants.d.ts +30 -0
  28. package/build/esm/constants.js +69 -0
  29. package/build/esm/dbHelpers.d.ts +43 -0
  30. package/build/esm/dbHelpers.js +154 -0
  31. package/build/esm/dbSeeder.d.ts +2 -0
  32. package/build/esm/dbSeeder.js +53 -0
  33. package/build/esm/dbTableHelpers.d.ts +11 -0
  34. package/build/esm/dbTableHelpers.js +99 -0
  35. package/build/esm/downloadHelpers.d.ts +2 -0
  36. package/build/esm/downloadHelpers.js +76 -0
  37. package/build/esm/index.d.ts +21 -0
  38. package/build/esm/index.js +21 -0
  39. package/build/esm/interfaces/ApiContext.d.ts +24 -0
  40. package/build/esm/interfaces/ApiContext.js +1 -0
  41. package/build/esm/interfaces/ApiContextInterface.d.ts +12 -0
  42. package/build/esm/interfaces/ApiContextInterface.js +1 -0
  43. package/build/esm/interfaces/BaseCoreActionsInterface.d.ts +38 -0
  44. package/build/esm/interfaces/BaseCoreActionsInterface.js +1 -0
  45. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +12 -0
  46. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.js +1 -0
  47. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +13 -0
  48. package/build/esm/interfaces/BaseCoreDoingWhatInterface.js +1 -0
  49. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +36 -0
  50. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  51. package/build/esm/interfaces/BaseCoreValidatorsInterface.d.ts +13 -0
  52. package/build/esm/interfaces/BaseCoreValidatorsInterface.js +1 -0
  53. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +39 -0
  54. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  55. package/build/esm/interfaces/BuildConfigOptions.d.ts +6 -0
  56. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  57. package/build/esm/interfaces/BuildDefaultResolversOptions.d.ts +17 -0
  58. package/build/esm/interfaces/BuildDefaultResolversOptions.js +1 -0
  59. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +6 -0
  60. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  61. package/build/esm/interfaces/CacheInterface.d.ts +15 -0
  62. package/build/esm/interfaces/CacheInterface.js +1 -0
  63. package/build/esm/interfaces/CommonValidatorArgs.d.ts +3 -0
  64. package/build/esm/interfaces/CommonValidatorArgs.js +1 -0
  65. package/build/esm/interfaces/CoreActionInterface.d.ts +14 -0
  66. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  67. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +11 -0
  68. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  69. package/build/esm/interfaces/CreateUserTokenResult.d.ts +4 -0
  70. package/build/esm/interfaces/CreateUserTokenResult.js +1 -0
  71. package/build/esm/interfaces/DatabaseOptions.d.ts +22 -0
  72. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  73. package/build/esm/interfaces/DatabaseReadInterface.d.ts +14 -0
  74. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  75. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +9 -0
  76. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  77. package/build/esm/interfaces/DownloadFileArgs.d.ts +6 -0
  78. package/build/esm/interfaces/DownloadFileArgs.js +1 -0
  79. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +19 -0
  80. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  81. package/build/esm/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
  82. package/build/esm/interfaces/JwtTokenSecretAndSettings.js +1 -0
  83. package/build/esm/interfaces/ListArgsInterface.d.ts +5 -0
  84. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  85. package/build/esm/interfaces/LoaderInterface.d.ts +4 -0
  86. package/build/esm/interfaces/LoaderInterface.js +1 -0
  87. package/build/esm/interfaces/PaginationInterface.d.ts +7 -0
  88. package/build/esm/interfaces/PaginationInterface.js +1 -0
  89. package/build/esm/interfaces/SortItemInterface.d.ts +4 -0
  90. package/build/esm/interfaces/SortItemInterface.js +1 -0
  91. package/build/esm/interfaces/UserTokenParams.d.ts +8 -0
  92. package/build/esm/interfaces/UserTokenParams.js +1 -0
  93. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +13 -0
  94. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  95. package/build/esm/interfaces/index.d.ts +28 -0
  96. package/build/esm/interfaces/index.js +27 -0
  97. package/build/esm/knexConfigBuilder.d.ts +1 -0
  98. package/build/esm/knexConfigBuilder.js +73 -0
  99. package/build/esm/passwordHelpers.d.ts +5 -0
  100. package/build/esm/passwordHelpers.js +22 -0
  101. package/build/esm/redisClient.d.ts +17 -0
  102. package/build/esm/redisClient.js +94 -0
  103. package/build/esm/resolversHelpers.d.ts +3 -0
  104. package/build/esm/resolversHelpers.js +59 -0
  105. package/build/esm/userToken.d.ts +8 -0
  106. package/build/esm/userToken.js +74 -0
  107. package/build/esm/utils.d.ts +2 -0
  108. package/build/esm/utils.js +13 -0
  109. package/package.json +13 -5
@@ -0,0 +1,273 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { castArray } from 'lodash';
11
+ import Checkit from 'checkit';
12
+ import check from 'check-types';
13
+ import isUUID from 'is-uuid';
14
+ import { OpResult, OP_RESULT_CODES } from '@sdflc/api-helpers';
15
+ import { createErrorOnCheckError } from './checkItHelpers';
16
+ import { ID_TYPES } from './constants';
17
+ const rulesSingleIntId = new Checkit({
18
+ id: [
19
+ {
20
+ rule: 'required',
21
+ message: 'ID is required',
22
+ },
23
+ {
24
+ rule: 'integer',
25
+ message: 'ID should be an integer',
26
+ },
27
+ ],
28
+ });
29
+ const rulesSingleUuidId = new Checkit({
30
+ id: [
31
+ {
32
+ rule: 'required',
33
+ message: 'ID is required',
34
+ },
35
+ {
36
+ rule: 'uuid',
37
+ message: 'ID should be an integer',
38
+ },
39
+ ],
40
+ });
41
+ const rulesSingleTextId = new Checkit({
42
+ id: [
43
+ {
44
+ rule: 'required',
45
+ message: 'ID is required',
46
+ },
47
+ {
48
+ rule: 'string',
49
+ message: 'ID should be a string',
50
+ },
51
+ ],
52
+ });
53
+ const rulesMultipleIntIds = new Checkit({
54
+ ids: [
55
+ {
56
+ rule: 'required',
57
+ message: 'IDs is required',
58
+ },
59
+ {
60
+ rule: 'array',
61
+ message: 'IDs should be an array of integer',
62
+ },
63
+ {
64
+ rule: (values) => {
65
+ const opResult = new OpResult();
66
+ castArray(values).forEach((value, idx) => {
67
+ if (!check.integer(value)) {
68
+ opResult.addError('ids', `The ids[${idx}] should be an integer`);
69
+ }
70
+ });
71
+ if (opResult.hasErrors()) {
72
+ opResult.setCode(OP_RESULT_CODES.VALIDATION_FAILED);
73
+ throw opResult;
74
+ }
75
+ },
76
+ },
77
+ ],
78
+ });
79
+ const rulesMultipleUuidIds = new Checkit({
80
+ ids: [
81
+ {
82
+ rule: 'required',
83
+ message: 'IDs is required',
84
+ },
85
+ {
86
+ rule: 'array',
87
+ message: 'IDs should be an array of UUIDs',
88
+ },
89
+ {
90
+ rule: (values) => {
91
+ const opResult = new OpResult();
92
+ castArray(values).forEach((value, idx) => {
93
+ if (!isUUID.v4(value)) {
94
+ opResult.addError('ids', `The ids[${idx}] should be a UUID of version 4`);
95
+ }
96
+ });
97
+ if (opResult.hasErrors()) {
98
+ opResult.setCode(OP_RESULT_CODES.VALIDATION_FAILED);
99
+ throw opResult;
100
+ }
101
+ },
102
+ },
103
+ ],
104
+ });
105
+ const rulesMultipleTextIds = new Checkit({
106
+ ids: [
107
+ {
108
+ rule: 'required',
109
+ message: 'IDs is required',
110
+ },
111
+ {
112
+ rule: 'array',
113
+ message: 'IDs should be an array of strings',
114
+ },
115
+ {
116
+ rule: (values) => {
117
+ const opResult = new OpResult();
118
+ castArray(values).forEach((value, idx) => {
119
+ if (!check.string(value)) {
120
+ opResult.addError('ids', `The ids[${idx}] should be a string`);
121
+ }
122
+ });
123
+ if (opResult.hasErrors()) {
124
+ opResult.setCode(OP_RESULT_CODES.VALIDATION_FAILED);
125
+ throw opResult;
126
+ }
127
+ },
128
+ },
129
+ ],
130
+ });
131
+ export const shouldHaveParams = (args) => {
132
+ const keys = Object.keys(args || {});
133
+ if (keys.length === 0) {
134
+ const result = new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
135
+ result.addError('', 'No params received');
136
+ return [result];
137
+ }
138
+ return [true];
139
+ };
140
+ export const shouldHaveId = (id) => {
141
+ if (!id) {
142
+ const result = new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
143
+ result.addError('', 'ID is required');
144
+ return [result];
145
+ }
146
+ return [true];
147
+ };
148
+ export const validateSingleIntId = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
149
+ const [result] = rulesSingleIntId.validateSync(args);
150
+ if (result) {
151
+ return [createErrorOnCheckError(result)];
152
+ }
153
+ return [true, {}];
154
+ });
155
+ export const validateSingleUuidId = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
156
+ const [result] = rulesSingleUuidId.validateSync(args);
157
+ if (result) {
158
+ return [createErrorOnCheckError(result)];
159
+ }
160
+ return [true, {}];
161
+ });
162
+ export const validateSingleTextId = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
163
+ const [result] = rulesSingleTextId.validateSync(args);
164
+ if (result) {
165
+ return [createErrorOnCheckError(result)];
166
+ }
167
+ return [true, {}];
168
+ });
169
+ export const validateMultipleIntIds = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
170
+ const [result] = rulesMultipleIntIds.validateSync(args);
171
+ if (result) {
172
+ return [createErrorOnCheckError(result)];
173
+ }
174
+ return [true, {}];
175
+ });
176
+ export const validateMultipleUuidIds = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
177
+ const [result] = rulesMultipleUuidIds.validateSync(args);
178
+ if (result) {
179
+ return [createErrorOnCheckError(result)];
180
+ }
181
+ return [true, {}];
182
+ });
183
+ export const validateMultipleTextIds = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
184
+ const [result] = rulesMultipleTextIds.validateSync(args);
185
+ if (result) {
186
+ return [createErrorOnCheckError(result)];
187
+ }
188
+ return [true, {}];
189
+ });
190
+ export const validateList = ({ rules }) => (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
191
+ const { filter } = args || {};
192
+ const [result] = rules.validateSync(filter);
193
+ if (result) {
194
+ return [createErrorOnCheckError(result)];
195
+ }
196
+ return [true, {}];
197
+ });
198
+ export const validateGet = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
199
+ const idType = opt.core.getIdType();
200
+ let rules = null;
201
+ switch (idType) {
202
+ case ID_TYPES.INT:
203
+ rules = rulesSingleIntId;
204
+ break;
205
+ case ID_TYPES.UUID:
206
+ rules = rulesSingleUuidId;
207
+ break;
208
+ case ID_TYPES.TEXT:
209
+ rules = rulesSingleTextId;
210
+ break;
211
+ }
212
+ if (!rules) {
213
+ return [true, {}];
214
+ }
215
+ const [result] = rules.validateSync(args);
216
+ if (result) {
217
+ return [createErrorOnCheckError(result)];
218
+ }
219
+ return [true, {}];
220
+ });
221
+ export const validateRemove = validateGet;
222
+ export const validateGetMany = (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
223
+ const idType = opt.core.getIdType();
224
+ let rules = null;
225
+ switch (idType) {
226
+ case ID_TYPES.INT:
227
+ rules = rulesMultipleIntIds;
228
+ break;
229
+ case ID_TYPES.UUID:
230
+ rules = rulesMultipleUuidIds;
231
+ break;
232
+ case ID_TYPES.TEXT:
233
+ rules = rulesMultipleTextIds;
234
+ break;
235
+ }
236
+ if (!rules) {
237
+ return [true, {}];
238
+ }
239
+ const [result] = rules.validateSync(args);
240
+ if (result) {
241
+ return [createErrorOnCheckError(result)];
242
+ }
243
+ return [true, {}];
244
+ });
245
+ export const validateRemoveMany = validateGetMany;
246
+ export const validateCreate = ({ rules }) => (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
247
+ const { params } = args || {};
248
+ const [paramsCheck] = shouldHaveParams(params);
249
+ if (paramsCheck !== true) {
250
+ return [paramsCheck, {}];
251
+ }
252
+ const [result] = rules.validateSync(params);
253
+ if (result) {
254
+ return [createErrorOnCheckError(result), {}];
255
+ }
256
+ return [true, {}];
257
+ });
258
+ export const validateUpdate = ({ rules }) => (args, opt) => __awaiter(void 0, void 0, void 0, function* () {
259
+ const { where, params } = args || {};
260
+ const [idCheck] = shouldHaveParams(where);
261
+ if (idCheck !== true) {
262
+ return [idCheck, {}];
263
+ }
264
+ const [paramsCheck] = shouldHaveParams(params);
265
+ if (paramsCheck !== true) {
266
+ return [paramsCheck, {}];
267
+ }
268
+ const [result] = rules.validateSync(params);
269
+ if (result) {
270
+ return [createErrorOnCheckError(result), {}];
271
+ }
272
+ return [true, {}];
273
+ });
@@ -0,0 +1,2 @@
1
+ import { BuildConfigOptions } from './interfaces';
2
+ export declare const buildConfig: (dirName: string, opt?: BuildConfigOptions) => any;
@@ -0,0 +1,28 @@
1
+ import { camelCase } from 'lodash';
2
+ import { join, resolve } from 'path';
3
+ import { config } from 'dotenv-safe';
4
+ export const buildConfig = (dirName, opt) => {
5
+ const opt2use = opt || {};
6
+ config({
7
+ path: resolve(dirName, opt2use.envFile || '.env'),
8
+ allowEmptyValues: opt2use.allowEmptyValues != null ? opt2use.allowEmptyValues : true,
9
+ example: join(dirName, opt2use.envFileExample || '.env.example'),
10
+ });
11
+ const env = Object.assign({ NODE_ENV: opt2use.defaultNodeEnv || 'development' }, process.env);
12
+ /**
13
+ * Creates an application settings consisting of environment variables
14
+ */
15
+ const envVars = Object.keys(env).reduce((acc, key) => {
16
+ let value = env[key];
17
+ const tryValue = (value || '').toLowerCase();
18
+ if (tryValue === 'false') {
19
+ value = false;
20
+ }
21
+ else if (tryValue === 'true') {
22
+ value = true;
23
+ }
24
+ acc[camelCase(key)] = value;
25
+ return acc;
26
+ }, {});
27
+ return Object.assign(Object.assign({}, envVars), { nodeEnv: env.NODE_ENV, isProduction: env.NODE_ENV === 'production' });
28
+ };
@@ -0,0 +1,30 @@
1
+ declare const FIELDS: any;
2
+ declare const ORDER_BYS: {
3
+ ASC: string;
4
+ DESC: string;
5
+ };
6
+ declare const HEADERS: any;
7
+ declare enum ID_TYPES {
8
+ UNKNOWN = 0,
9
+ INT = 1,
10
+ UUID = 2,
11
+ TEXT = 3
12
+ }
13
+ declare const ID_FIELD: any;
14
+ declare const DEFAULT_ORDER_NO = "10000000";
15
+ declare const DEFAULT_ORDER_NO_STEP = "1000";
16
+ declare const DEFAULT_JWT_ALGORITHM = "HS256";
17
+ declare const DEFAULT_JWT_ISSUER = "microservices-auth";
18
+ declare const ACTIONS: {
19
+ LIST: string;
20
+ GET: string;
21
+ GET_MANY: string;
22
+ CREATE: string;
23
+ CREATE_MANY: string;
24
+ UPDATE: string;
25
+ UPDATE_MANY: string;
26
+ SET: string;
27
+ REMOVE: string;
28
+ REMOVE_MANY: string;
29
+ };
30
+ export { ID_FIELD, FIELDS, ORDER_BYS, HEADERS, DEFAULT_ORDER_NO, DEFAULT_ORDER_NO_STEP, ID_TYPES, DEFAULT_JWT_ALGORITHM, DEFAULT_JWT_ISSUER, ACTIONS, };
@@ -0,0 +1,69 @@
1
+ const FIELDS = {
2
+ ID: 'id',
3
+ STATUS: 'status',
4
+ VERSION: 'version',
5
+ CREATED_BY: 'created_by',
6
+ UPDATED_BY: 'updated_by',
7
+ REMOVED_BY: 'removed_by',
8
+ CREATED_AT: 'created_at',
9
+ UPDATED_AT: 'updated_at',
10
+ REMOVED_AT: 'removed_at',
11
+ REMOVED_AT_STR: 'removed_at_str',
12
+ LANG: 'LANG',
13
+ ACCOUNT_ID: 'account_id',
14
+ ROLE_ID: 'role_id',
15
+ USER_ID: 'user_id',
16
+ ORDER_NO: 'order_no',
17
+ SPACE_ID: 'space_id',
18
+ DISPLAY_NAME: 'display_name',
19
+ NAME: 'name',
20
+ USERNAME: 'username',
21
+ EMAIL: 'email',
22
+ PHONE: 'phone',
23
+ };
24
+ const ORDER_BYS = {
25
+ ASC: 'asc',
26
+ DESC: 'desc',
27
+ };
28
+ const HEADERS = {
29
+ AUTHORIZATION: 'authorization',
30
+ FINGERPRINT: 'x-fingerprint',
31
+ SPACE_ID: 'x-space-id',
32
+ API_KEY: 'x-api-key',
33
+ MANAGEMENT_API_KEY: 'x-management-api-key',
34
+ ACCOUNT_ID: 'x-account-id',
35
+ ROLE_ID: 'x-role-id',
36
+ USER_ID: 'x-user-id',
37
+ USER_AGENT: 'user-agent',
38
+ REFERER: 'referer',
39
+ IP_ADDRESS: 'x-forwarded-for',
40
+ ACCEPT_LANGUAGE: 'accept-language',
41
+ REQUESTED_LANGUAGE: 'x-lang',
42
+ CONTENT_TYPE: 'content-type',
43
+ CONTENT_LENGTH: 'content-length',
44
+ };
45
+ var ID_TYPES;
46
+ (function (ID_TYPES) {
47
+ ID_TYPES[ID_TYPES["UNKNOWN"] = 0] = "UNKNOWN";
48
+ ID_TYPES[ID_TYPES["INT"] = 1] = "INT";
49
+ ID_TYPES[ID_TYPES["UUID"] = 2] = "UUID";
50
+ ID_TYPES[ID_TYPES["TEXT"] = 3] = "TEXT";
51
+ })(ID_TYPES || (ID_TYPES = {}));
52
+ const ID_FIELD = FIELDS.ID;
53
+ const DEFAULT_ORDER_NO = '10000000';
54
+ const DEFAULT_ORDER_NO_STEP = '1000';
55
+ const DEFAULT_JWT_ALGORITHM = 'HS256';
56
+ const DEFAULT_JWT_ISSUER = 'microservices-auth';
57
+ const ACTIONS = {
58
+ LIST: 'LIST',
59
+ GET: 'GET',
60
+ GET_MANY: 'GET_MANY',
61
+ CREATE: 'CREATE',
62
+ CREATE_MANY: 'CREATE_MANY',
63
+ UPDATE: 'UPDATE',
64
+ UPDATE_MANY: 'UPDATE_MANY',
65
+ SET: 'SET',
66
+ REMOVE: 'REMOVE',
67
+ REMOVE_MANY: 'REMOVE_MANY',
68
+ };
69
+ export { ID_FIELD, FIELDS, ORDER_BYS, HEADERS, DEFAULT_ORDER_NO, DEFAULT_ORDER_NO_STEP, ID_TYPES, DEFAULT_JWT_ALGORITHM, DEFAULT_JWT_ISSUER, ACTIONS, };
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Removes all the records from provided table.
3
+ * If appSettings has cleanTable object with table names then
4
+ * it is used to add extra filters to clear the table to avoid for example users data
5
+ * @param table Name of table from which to remove all the records
6
+ * @param knexHandle Knex handle object with configured connection to DB
7
+ * @param appSettings settings with db related information
8
+ */
9
+ declare const dbCleanTable: (table: string, knexHandle: any, appSettings: any) => Promise<void>;
10
+ /**
11
+ * Returns a list of tables in db schedm specified in settings
12
+ * @param knexHandle Knex handle object with configured connection to DB
13
+ * @param appSettings settings with db related information
14
+ * @returns arrays of table names in the provided db schema
15
+ */
16
+ declare const dbListTables: (knexHandle: any, appSettings: any) => Promise<any>;
17
+ /**
18
+ * Removes all the records from provided list of tables
19
+ * @param tablesToClean array of table names
20
+ * @param knexHandle Knex handle object with configured connection to DB
21
+ * @param appSettings settings with db related information
22
+ * @returns promise
23
+ */
24
+ declare const dbClean: (tablesToClean: any[], knexHandle: any, appSettings: any) => Promise<unknown>;
25
+ /**
26
+ * Selects all the tables in the schema and drops them.
27
+ * This approach does not work in case we have constraints.
28
+ * TODO: Remove all constraints and then drop tables.
29
+ */
30
+ declare const dbWipe: (knexHandle: any, appSettings: any) => any;
31
+ /**
32
+ * Drop all tables, run migrations, then seed
33
+ */
34
+ declare const dbReset: (knexHandle: any, appSettings: any) => any;
35
+ /**
36
+ * Go from array of objects which contain keys of object names which have an array value of seeded objects
37
+ * to a single object with keys of object names and arrays of seeded objects
38
+ * ie from [{table1: [], table2: [] }, { table3: [] }]
39
+ * to { table1: [], table2: [], table3: []}
40
+ */
41
+ declare const dbTransformSeedsToObject: (generatedSeedArrays: any[]) => any;
42
+ declare const dbRunMigrations: (knexHandle: any, appSettings: any) => any;
43
+ export { dbCleanTable, dbListTables, dbClean, dbWipe, dbReset, dbTransformSeedsToObject, dbRunMigrations };
@@ -0,0 +1,154 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import BPromise from 'bluebird';
11
+ import { reduce } from 'lodash';
12
+ const SQLS = {
13
+ pg: {
14
+ listTablesSchema: (appSettings) => `
15
+ SELECT TABLE_NAME as table_name
16
+ FROM INFORMATION_SCHEMA.TABLES
17
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
18
+ `,
19
+ listTables: () => `
20
+ SELECT TABLE_NAME as table_name
21
+ FROM INFORMATION_SCHEMA.TABLES
22
+ `,
23
+ dropTablesSchema: (appSettings) => `
24
+ SELECT 'DROP TABLE IF EXISTS ${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}.' || TABLE_NAME || ';' as cmd
25
+ FROM INFORMATION_SCHEMA.TABLES
26
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
27
+ `,
28
+ dropTables: () => `
29
+ SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd
30
+ FROM INFORMATION_SCHEMA.TABLES';
31
+ `,
32
+ },
33
+ mssql: {
34
+ listTablesSchema: (appSettings) => `
35
+ SELECT TABLE_NAME as table_name
36
+ FROM INFORMATION_SCHEMA.TABLES
37
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
38
+ `,
39
+ listTables: () => `
40
+ SELECT TABLE_NAME as table_name
41
+ FROM INFORMATION_SCHEMA.TABLES
42
+ `,
43
+ dropTablesSchema: (appSettings) => `
44
+ SELECT 'DROP TABLE IF EXISTS [${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}].[' + TABLE_NAME + '];' as cmd
45
+ FROM INFORMATION_SCHEMA.TABLES
46
+ WHERE TABLE_SCHEMA = '${appSettings === null || appSettings === void 0 ? void 0 : appSettings.dbSchema}';
47
+ `,
48
+ dropTables: () => `
49
+ SELECT 'DROP TABLE IF EXISTS ' + TABLE_NAME + ';' as cmd
50
+ FROM INFORMATION_SCHEMA.TABLES';
51
+ `,
52
+ },
53
+ };
54
+ /**
55
+ * Removes all the records from provided table.
56
+ * If appSettings has cleanTable object with table names then
57
+ * it is used to add extra filters to clear the table to avoid for example users data
58
+ * @param table Name of table from which to remove all the records
59
+ * @param knexHandle Knex handle object with configured connection to DB
60
+ * @param appSettings settings with db related information
61
+ */
62
+ const dbCleanTable = (table, knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
63
+ var _a;
64
+ const query = knexHandle(table).withSchema(appSettings.dbSchema).delete();
65
+ const cleanTableFilters = (_a = appSettings === null || appSettings === void 0 ? void 0 : appSettings.cleanTableFilters) === null || _a === void 0 ? void 0 : _a[table];
66
+ if (cleanTableFilters != undefined) {
67
+ if (Array.isArray(cleanTableFilters.where)) {
68
+ cleanTableFilters.where.forEach((whereItem) => {
69
+ query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
70
+ });
71
+ }
72
+ }
73
+ yield query;
74
+ });
75
+ /**
76
+ * Returns a list of tables in db schedm specified in settings
77
+ * @param knexHandle Knex handle object with configured connection to DB
78
+ * @param appSettings settings with db related information
79
+ * @returns arrays of table names in the provided db schema
80
+ */
81
+ const dbListTables = (knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
82
+ const skipTables = (appSettings || {}).skipTables || [];
83
+ let query = SQLS[appSettings.dbType].listTablesSchema(appSettings);
84
+ if (!appSettings.dbSchema) {
85
+ query = SQLS[appSettings.dbType].listTables(appSettings);
86
+ }
87
+ const tables = yield knexHandle.raw(query);
88
+ return (tables.rows || [])
89
+ .map((row) => row.table_name)
90
+ .filter((table) => skipTables.indexOf(table) === -1);
91
+ });
92
+ /**
93
+ * Removes all the records from provided list of tables
94
+ * @param tablesToClean array of table names
95
+ * @param knexHandle Knex handle object with configured connection to DB
96
+ * @param appSettings settings with db related information
97
+ * @returns promise
98
+ */
99
+ const dbClean = (tablesToClean, knexHandle, appSettings) => __awaiter(void 0, void 0, void 0, function* () {
100
+ for (let idx = 0, len = tablesToClean.length; idx < len; ++idx) {
101
+ yield dbCleanTable(tablesToClean[idx], knexHandle, appSettings);
102
+ }
103
+ return new BPromise((resolve) => {
104
+ resolve(tablesToClean);
105
+ });
106
+ });
107
+ /**
108
+ * Selects all the tables in the schema and drops them.
109
+ * This approach does not work in case we have constraints.
110
+ * TODO: Remove all constraints and then drop tables.
111
+ */
112
+ const dbWipe = (knexHandle, appSettings) => {
113
+ let query = SQLS[appSettings.dbType].dropTablesSchema(appSettings);
114
+ if (!appSettings.dbSchema) {
115
+ query = SQLS[appSettings.dbType].dropTables(appSettings);
116
+ }
117
+ return knexHandle
118
+ .raw(query)
119
+ .then((result) => result.rows.map((r) => r.cmd))
120
+ .then((commands) => BPromise.each(commands, (cmd) => knexHandle.raw(cmd)));
121
+ };
122
+ /**
123
+ * Drop all tables, run migrations, then seed
124
+ */
125
+ const dbReset = (knexHandle, appSettings) => {
126
+ return dbWipe(knexHandle, appSettings)
127
+ .then(() => dbRunMigrations(knexHandle, appSettings))
128
+ .catch((error) => console.log('An exception has occurred on resetting database: ', error));
129
+ };
130
+ /**
131
+ * Go from array of objects which contain keys of object names which have an array value of seeded objects
132
+ * to a single object with keys of object names and arrays of seeded objects
133
+ * ie from [{table1: [], table2: [] }, { table3: [] }]
134
+ * to { table1: [], table2: [], table3: []}
135
+ */
136
+ const dbTransformSeedsToObject = (generatedSeedArrays) => reduce(generatedSeedArrays, (acc, cur) => {
137
+ for (const key in cur) {
138
+ acc[key] = cur[key];
139
+ }
140
+ return acc;
141
+ }, {});
142
+ const dbRunMigrations = (knexHandle, appSettings) => {
143
+ return knexHandle.migrate
144
+ .latest()
145
+ .then((result) => __awaiter(void 0, void 0, void 0, function* () {
146
+ if (appSettings && appSettings.runDbSeed && result[1].length > 0) {
147
+ yield knexHandle.seed.run();
148
+ }
149
+ console.log('Ran', result[1].length, 'migration(s)');
150
+ return knexHandle.migrate.currentVersion();
151
+ }))
152
+ .then((version) => console.log('Current version of database: ', version));
153
+ };
154
+ export { dbCleanTable, dbListTables, dbClean, dbWipe, dbReset, dbTransformSeedsToObject, dbRunMigrations };
@@ -0,0 +1,2 @@
1
+ declare const dbSeed: (dirname: string, seedFiles: any, knexHandle: any, config: any) => Promise<any>;
2
+ export { dbSeed };
@@ -0,0 +1,53 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import path from 'path';
11
+ import { camelCase, flatten, map } from 'lodash';
12
+ import { dbClean } from './dbHelpers';
13
+ const generateSeeds = (dirname, seedFiles) => __awaiter(void 0, void 0, void 0, function* () {
14
+ let seedGroups = [];
15
+ const seedFileNames = flatten(seedFiles);
16
+ const seedFnExports = yield Promise.all(map(seedFileNames, (filename) => import(path.join(dirname, `./objects/${filename}.js`))));
17
+ const seedFns = map(seedFnExports, 'default');
18
+ const seedFnsMap = {};
19
+ for (let i = 0; i < seedFileNames.length; i++) {
20
+ const seedFileName = seedFileNames[i];
21
+ seedFnsMap[seedFileName] = seedFns[i];
22
+ }
23
+ seedFiles.reduce((seeds, fileGroup) => {
24
+ seedGroups = seedGroups.concat(fileGroup.reduce((group, filename) => {
25
+ const seedFn = seedFnsMap[filename];
26
+ const seed = seedFn(seeds);
27
+ const filenameCamel = camelCase(filename);
28
+ seeds[filenameCamel] = seed;
29
+ return Object.assign({ [filenameCamel]: seed }, group);
30
+ }, {}));
31
+ return seeds;
32
+ }, {});
33
+ return seedGroups;
34
+ });
35
+ const removeSeedsFromDb = (seedFiles, knexHandle, config) => {
36
+ const tablesToReset = flatten(seedFiles).reverse();
37
+ console.log('Deleting records from tables: ', tablesToReset);
38
+ return dbClean(tablesToReset, knexHandle, config);
39
+ };
40
+ const insertRecords = (seedGroups, knexHandle, config) => {
41
+ const { dbSchema } = config || {};
42
+ console.log('Inserting seeds records tables tables...');
43
+ return seedGroups.reduce((previousGroup, group) => __awaiter(void 0, void 0, void 0, function* () {
44
+ yield previousGroup;
45
+ return Promise.all(Object.keys(group).map((table) => knexHandle(table).withSchema(dbSchema).insert(group[table])));
46
+ }), Promise.resolve());
47
+ };
48
+ const dbSeed = (dirname, seedFiles, knexHandle, config) => __awaiter(void 0, void 0, void 0, function* () {
49
+ const groups = yield generateSeeds(dirname, seedFiles);
50
+ yield removeSeedsFromDb(seedFiles, knexHandle, config);
51
+ return yield insertRecords(groups, knexHandle, config);
52
+ });
53
+ export { dbSeed };
@@ -0,0 +1,11 @@
1
+ import { DbFieldAddDefaultInterface } from './interfaces';
2
+ export declare const dbFieldAddDefaults: (table: any, opt?: DbFieldAddDefaultInterface) => void;
3
+ export declare const addOrderNo: (table: any, opt?: any) => any;
4
+ export declare const addAmount: (table: any, fieldName: string) => any;
5
+ export declare const addSpaceId: (table: any, opt?: any) => any;
6
+ export declare const addUserId: (table: any, opt?: any) => any;
7
+ export declare const addAccountId: (table: any, opt?: any) => any;
8
+ export declare const addLang: (table: any, opt?: any) => any;
9
+ export declare const defaultFields: (opt?: any) => {
10
+ [x: number]: string;
11
+ };