@sdflc/backend-helpers 1.0.112 → 1.0.114

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 (214) hide show
  1. package/README.md +1422 -146
  2. package/build/BaseController.d.ts +20 -0
  3. package/build/BaseController.js +64 -0
  4. package/build/BaseCore.d.ts +586 -33
  5. package/build/BaseCore.js +821 -127
  6. package/build/BaseExternalApiGateway.d.ts +16 -0
  7. package/build/BaseExternalApiGateway.js +54 -0
  8. package/build/BaseGateway.d.ts +455 -17
  9. package/build/BaseGateway.js +502 -56
  10. package/build/BaseRestApiCrudController.d.ts +37 -0
  11. package/build/BaseRestApiCrudController.js +134 -0
  12. package/build/DataCache.d.ts +116 -5
  13. package/build/DataCache.js +144 -22
  14. package/build/Database.d.ts +165 -4
  15. package/build/Database.js +224 -51
  16. package/build/DbMigratorAndSeeder.d.ts +127 -26
  17. package/build/DbMigratorAndSeeder.js +180 -69
  18. package/build/IpRateLimiter.d.ts +105 -0
  19. package/build/IpRateLimiter.js +104 -0
  20. package/build/RedisDataLoader.d.ts +144 -21
  21. package/build/RedisDataLoader.js +178 -49
  22. package/build/apiContext.d.ts +0 -8
  23. package/build/apiContext.js +30 -32
  24. package/build/checkItHelpers.d.ts +32 -0
  25. package/build/checkItHelpers.js +73 -7
  26. package/build/commonValidators.d.ts +107 -16
  27. package/build/commonValidators.js +211 -106
  28. package/build/configBuilder.d.ts +23 -0
  29. package/build/configBuilder.js +73 -0
  30. package/build/constants.d.ts +134 -17
  31. package/build/constants.js +95 -15
  32. package/build/dbHelpers.d.ts +89 -29
  33. package/build/dbHelpers.js +175 -86
  34. package/build/dbSeeder.d.ts +10 -1
  35. package/build/dbSeeder.js +80 -15
  36. package/build/dbTableHelpers.d.ts +122 -5
  37. package/build/dbTableHelpers.js +151 -13
  38. package/build/downloadHelpers.d.ts +24 -1
  39. package/build/downloadHelpers.js +51 -21
  40. package/build/esm/BaseController.d.ts +20 -0
  41. package/build/esm/BaseController.js +58 -0
  42. package/build/esm/BaseCore.d.ts +586 -33
  43. package/build/esm/BaseCore.js +812 -118
  44. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  45. package/build/esm/BaseExternalApiGateway.js +48 -0
  46. package/build/esm/BaseGateway.d.ts +455 -17
  47. package/build/esm/BaseGateway.js +503 -57
  48. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  49. package/build/esm/BaseRestApiCrudController.js +131 -0
  50. package/build/esm/DataCache.d.ts +116 -5
  51. package/build/esm/DataCache.js +142 -20
  52. package/build/esm/Database.d.ts +165 -4
  53. package/build/esm/Database.js +224 -51
  54. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  55. package/build/esm/DbMigratorAndSeeder.js +184 -71
  56. package/build/esm/IpRateLimiter.d.ts +105 -0
  57. package/build/esm/IpRateLimiter.js +100 -0
  58. package/build/esm/RedisDataLoader.d.ts +144 -21
  59. package/build/esm/RedisDataLoader.js +179 -50
  60. package/build/esm/apiContext.d.ts +0 -8
  61. package/build/esm/apiContext.js +30 -32
  62. package/build/esm/checkItHelpers.d.ts +32 -0
  63. package/build/esm/checkItHelpers.js +73 -7
  64. package/build/esm/commonValidators.d.ts +107 -16
  65. package/build/esm/commonValidators.js +209 -105
  66. package/build/esm/configBuilder.d.ts +23 -0
  67. package/build/esm/configBuilder.js +69 -0
  68. package/build/esm/constants.d.ts +134 -17
  69. package/build/esm/constants.js +94 -14
  70. package/build/esm/dbHelpers.d.ts +89 -29
  71. package/build/esm/dbHelpers.js +171 -81
  72. package/build/esm/dbSeeder.d.ts +10 -1
  73. package/build/esm/dbSeeder.js +81 -16
  74. package/build/esm/dbTableHelpers.d.ts +122 -5
  75. package/build/esm/dbTableHelpers.js +152 -14
  76. package/build/esm/downloadHelpers.d.ts +24 -1
  77. package/build/esm/downloadHelpers.js +51 -21
  78. package/build/esm/index.d.ts +6 -2
  79. package/build/esm/index.js +6 -2
  80. package/build/esm/interfaces/ApiContext.d.ts +33 -3
  81. package/build/esm/interfaces/ApiContext.js +1 -0
  82. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  83. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  84. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  85. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  86. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  87. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +146 -9
  88. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  89. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  90. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  91. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  92. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  93. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  94. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  95. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  96. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  97. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  98. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  99. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  100. package/build/esm/interfaces/CacheInterface.js +1 -0
  101. package/build/esm/interfaces/CoreActionInterface.d.ts +60 -0
  102. package/build/esm/interfaces/CoreActionInterface.js +1 -0
  103. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  104. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  105. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  106. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  107. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  108. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  109. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  110. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  111. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  112. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  113. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  114. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  115. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  116. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  117. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  118. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  119. package/build/esm/interfaces/LoaderInterface.js +1 -0
  120. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  121. package/build/esm/interfaces/UserTokenParams.js +1 -0
  122. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  123. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  124. package/build/esm/interfaces/index.d.ts +4 -0
  125. package/build/esm/interfaces/index.js +4 -0
  126. package/build/esm/knexConfigBuilder.d.ts +25 -0
  127. package/build/esm/knexConfigBuilder.js +100 -36
  128. package/build/esm/parseIds.d.ts +6 -0
  129. package/build/esm/parseIds.js +13 -0
  130. package/build/esm/passwordHelpers.d.ts +22 -0
  131. package/build/esm/passwordHelpers.js +40 -8
  132. package/build/esm/redisClient.d.ts +57 -4
  133. package/build/esm/redisClient.js +40 -54
  134. package/build/esm/resolveClientIp.d.ts +15 -0
  135. package/build/esm/resolveClientIp.js +34 -0
  136. package/build/esm/resolversHelpers.d.ts +21 -1
  137. package/build/esm/resolversHelpers.js +48 -26
  138. package/build/esm/userToken.d.ts +50 -1
  139. package/build/esm/userToken.js +85 -20
  140. package/build/esm/utils.d.ts +20 -2
  141. package/build/esm/utils.js +23 -13
  142. package/build/index.d.ts +6 -2
  143. package/build/index.js +6 -2
  144. package/build/interfaces/ApiContext.d.ts +33 -3
  145. package/build/interfaces/ApiContext.js +1 -0
  146. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  147. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  148. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  149. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  150. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  151. package/build/interfaces/BaseCorePropsInterface.d.ts +146 -9
  152. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  153. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  154. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  155. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  156. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  157. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  158. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  159. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  160. package/build/interfaces/BuildConfigOptions.js +1 -0
  161. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  162. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  163. package/build/interfaces/CacheInterface.d.ts +18 -1
  164. package/build/interfaces/CacheInterface.js +1 -0
  165. package/build/interfaces/CoreActionInterface.d.ts +60 -0
  166. package/build/interfaces/CoreActionInterface.js +1 -0
  167. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  168. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  169. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  170. package/build/interfaces/DataCachePropsInterface.js +3 -0
  171. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  172. package/build/interfaces/DatabaseOptions.js +1 -0
  173. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  174. package/build/interfaces/DatabaseReadInterface.js +1 -0
  175. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  176. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  177. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  178. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  179. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  180. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  181. package/build/interfaces/ListArgsInterface.js +1 -0
  182. package/build/interfaces/LoaderInterface.d.ts +36 -1
  183. package/build/interfaces/LoaderInterface.js +1 -0
  184. package/build/interfaces/UserTokenParams.d.ts +23 -5
  185. package/build/interfaces/UserTokenParams.js +1 -0
  186. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  187. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  188. package/build/interfaces/index.d.ts +4 -0
  189. package/build/interfaces/index.js +4 -0
  190. package/build/knexConfigBuilder.d.ts +25 -0
  191. package/build/knexConfigBuilder.js +99 -35
  192. package/build/parseIds.d.ts +6 -0
  193. package/build/parseIds.js +17 -0
  194. package/build/passwordHelpers.d.ts +22 -0
  195. package/build/passwordHelpers.js +40 -8
  196. package/build/redisClient.d.ts +57 -4
  197. package/build/redisClient.js +40 -54
  198. package/build/resolveClientIp.d.ts +15 -0
  199. package/build/resolveClientIp.js +38 -0
  200. package/build/resolversHelpers.d.ts +21 -1
  201. package/build/resolversHelpers.js +48 -26
  202. package/build/userToken.d.ts +50 -1
  203. package/build/userToken.js +85 -20
  204. package/build/utils.d.ts +20 -2
  205. package/build/utils.js +24 -16
  206. package/package.json +19 -18
  207. package/build/baseController.d.ts +0 -17
  208. package/build/baseController.js +0 -64
  209. package/build/configBulder.d.ts +0 -2
  210. package/build/configBulder.js +0 -36
  211. package/build/esm/baseController.d.ts +0 -17
  212. package/build/esm/baseController.js +0 -58
  213. package/build/esm/configBulder.d.ts +0 -2
  214. package/build/esm/configBulder.js +0 -32
@@ -1,156 +1,245 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ // ./src/dbHelpers.ts
5
3
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = void 0;
7
- const bluebird_1 = __importDefault(require("bluebird"));
4
+ exports.dbRunMigrations = exports.dbTransformSeedsToObject = exports.dbReset = exports.dbWipe = exports.dbClean = exports.dbListTables = exports.dbCleanTable = exports.assertSupportedDbType = exports.sanitiseIdentifier = void 0;
8
5
  const lodash_1 = require("lodash");
6
+ /**
7
+ * Database utility helpers for development, testing, and migration tooling.
8
+ *
9
+ * These functions are NOT intended for production runtime use — they are
10
+ * designed for test setup/teardown, CI pipelines, and local development.
11
+ *
12
+ * Supported database types: 'pg', 'mssql'
13
+ * All functions accept a raw Knex handle (not a Database instance) since
14
+ * they operate outside the normal request lifecycle.
15
+ */
16
+ // ─── SQL templates ────────────────────────────────────────────────────────────
17
+ /**
18
+ * Raw SQL query templates per database type.
19
+ * Schema names are injected via sanitiseIdentifier() before use to prevent
20
+ * SQL injection — schema names must be alphanumeric + underscores only.
21
+ *
22
+ * Fix: removed stray `'` before `;` in pg.dropTables and mssql.dropTables
23
+ * which produced invalid SQL.
24
+ */
9
25
  const SQLS = {
10
26
  pg: {
11
27
  listTablesSchema: (appSettings) => `
12
28
  SELECT TABLE_NAME as table_name
13
29
  FROM INFORMATION_SCHEMA.TABLES
14
- WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
30
+ WHERE TABLE_SCHEMA = '${(0, exports.sanitiseIdentifier)(appSettings?.dbSchema)}';
15
31
  `,
16
32
  listTables: () => `
17
33
  SELECT TABLE_NAME as table_name
18
- FROM INFORMATION_SCHEMA.TABLES
34
+ FROM INFORMATION_SCHEMA.TABLES;
19
35
  `,
20
36
  dropTablesSchema: (appSettings) => `
21
- SELECT 'DROP TABLE IF EXISTS ${appSettings?.dbSchema}.' || TABLE_NAME || ';' as cmd
22
- FROM INFORMATION_SCHEMA.TABLES
23
- WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
37
+ SELECT 'DROP TABLE IF EXISTS ${(0, exports.sanitiseIdentifier)(appSettings?.dbSchema)}.' || TABLE_NAME || ';' as cmd
38
+ FROM INFORMATION_SCHEMA.TABLES
39
+ WHERE TABLE_SCHEMA = '${(0, exports.sanitiseIdentifier)(appSettings?.dbSchema)}';
24
40
  `,
25
41
  dropTables: () => `
26
42
  SELECT 'DROP TABLE IF EXISTS ' || TABLE_NAME || ';' as cmd
27
- FROM INFORMATION_SCHEMA.TABLES';
43
+ FROM INFORMATION_SCHEMA.TABLES;
28
44
  `,
29
45
  },
30
46
  mssql: {
31
47
  listTablesSchema: (appSettings) => `
32
48
  SELECT TABLE_NAME as table_name
33
49
  FROM INFORMATION_SCHEMA.TABLES
34
- WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
50
+ WHERE TABLE_SCHEMA = '${(0, exports.sanitiseIdentifier)(appSettings?.dbSchema)}';
35
51
  `,
36
52
  listTables: () => `
37
53
  SELECT TABLE_NAME as table_name
38
- FROM INFORMATION_SCHEMA.TABLES
54
+ FROM INFORMATION_SCHEMA.TABLES;
39
55
  `,
40
56
  dropTablesSchema: (appSettings) => `
41
- SELECT 'DROP TABLE IF EXISTS [${appSettings?.dbSchema}].[' + TABLE_NAME + '];' as cmd
57
+ SELECT 'DROP TABLE IF EXISTS [${(0, exports.sanitiseIdentifier)(appSettings?.dbSchema)}].[' + TABLE_NAME + '];' as cmd
42
58
  FROM INFORMATION_SCHEMA.TABLES
43
- WHERE TABLE_SCHEMA = '${appSettings?.dbSchema}';
59
+ WHERE TABLE_SCHEMA = '${(0, exports.sanitiseIdentifier)(appSettings?.dbSchema)}';
44
60
  `,
45
61
  dropTables: () => `
46
62
  SELECT 'DROP TABLE IF EXISTS ' + TABLE_NAME + ';' as cmd
47
- FROM INFORMATION_SCHEMA.TABLES';
63
+ FROM INFORMATION_SCHEMA.TABLES;
48
64
  `,
49
65
  },
50
66
  };
67
+ // ─── Internal helpers ─────────────────────────────────────────────────────────
68
+ /**
69
+ * Validates that a database identifier (schema name, table name) contains
70
+ * only safe characters — alphanumeric and underscores.
71
+ * Throws if the identifier contains anything else to prevent SQL injection
72
+ * via template-interpolated schema names in SQLS above.
73
+ *
74
+ * @param identifier Schema or table name to validate
75
+ */
76
+ const sanitiseIdentifier = (identifier) => {
77
+ if (!identifier)
78
+ return '';
79
+ if (!/^[a-zA-Z0-9_]+$/.test(identifier)) {
80
+ throw new Error(`Invalid database identifier: "${identifier}". ` + `Only alphanumeric characters and underscores are allowed.`);
81
+ }
82
+ return identifier;
83
+ };
84
+ exports.sanitiseIdentifier = sanitiseIdentifier;
51
85
  /**
52
- * Removes all the records from provided table.
53
- * If appSettings has cleanTable object with table names then
54
- * it is used to add extra filters to clear the table to avoid for example users data
55
- * @param table Name of table from which to remove all the records
56
- * @param knexHandle Knex handle object with configured connection to DB
57
- * @param appSettings settings with db related information
86
+ * Guards that the provided dbType is supported by SQLS.
87
+ * Throws a clear error rather than letting the caller hit
88
+ * `TypeError: Cannot read properties of undefined`.
89
+ *
90
+ * @param dbType Database type string from appSettings
91
+ */
92
+ const assertSupportedDbType = (dbType) => {
93
+ if (!SQLS[dbType]) {
94
+ throw new Error(`Unsupported database type: "${dbType}". ` + `Supported types are: ${Object.keys(SQLS).join(', ')}`);
95
+ }
96
+ };
97
+ exports.assertSupportedDbType = assertSupportedDbType;
98
+ // ─── Exported utilities ───────────────────────────────────────────────────────
99
+ /**
100
+ * Removes all records from the specified table.
101
+ *
102
+ * If `appSettings.cleanTableFilters[table]` is configured, applies additional
103
+ * WHERE conditions before deleting — useful for preserving seed/system records
104
+ * while clearing user-generated data during test teardown.
105
+ *
106
+ * @param table Name of the table to clean
107
+ * @param knexHandle Knex instance with configured DB connection
108
+ * @param appSettings Settings object with dbSchema and optional cleanTableFilters
58
109
  */
59
110
  const dbCleanTable = async (table, knexHandle, appSettings) => {
60
111
  const query = knexHandle(table).withSchema(appSettings.dbSchema).delete();
61
112
  const cleanTableFilters = appSettings?.cleanTableFilters?.[table];
62
- if (cleanTableFilters != undefined) {
63
- if (Array.isArray(cleanTableFilters.where)) {
64
- cleanTableFilters.where.forEach((whereItem) => {
65
- query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
66
- });
67
- }
113
+ if (cleanTableFilters != null && Array.isArray(cleanTableFilters.where)) {
114
+ cleanTableFilters.where.forEach((whereItem) => {
115
+ query.where(whereItem.fieldName, whereItem.operand, whereItem.value);
116
+ });
68
117
  }
69
118
  await query;
70
119
  };
71
120
  exports.dbCleanTable = dbCleanTable;
72
121
  /**
73
- * Returns a list of tables in db schedm specified in settings
74
- * @param knexHandle Knex handle object with configured connection to DB
75
- * @param appSettings settings with db related information
76
- * @returns arrays of table names in the provided db schema
122
+ * Returns the list of table names in the configured schema.
123
+ * Tables listed in `appSettings.skipTables` are excluded from the result.
124
+ *
125
+ * Uses schema-scoped query when `appSettings.dbSchema` is set,
126
+ * otherwise queries all tables in the database.
127
+ *
128
+ * Handles both pg (result.rows array) and mssql (direct array) result formats.
129
+ *
130
+ * @param knexHandle Knex instance with configured DB connection
131
+ * @param appSettings Settings object with dbType, dbSchema, and optional skipTables
77
132
  */
78
133
  const dbListTables = async (knexHandle, appSettings) => {
79
134
  const skipTables = (appSettings || {}).skipTables || [];
80
- let query = SQLS[appSettings.dbType].listTablesSchema(appSettings);
81
- if (!appSettings.dbSchema) {
82
- query = SQLS[appSettings.dbType].listTables(appSettings);
83
- }
135
+ (0, exports.assertSupportedDbType)(appSettings.dbType);
136
+ const query = appSettings.dbSchema
137
+ ? SQLS[appSettings.dbType].listTablesSchema(appSettings)
138
+ : SQLS[appSettings.dbType].listTables(appSettings);
84
139
  const tables = await knexHandle.raw(query);
85
- return (tables.rows || [])
86
- .map((row) => row.table_name)
87
- .filter((table) => skipTables.indexOf(table) === -1);
140
+ // pg returns { rows: [...] }, mssql and others return the array directly
141
+ const rows = Array.isArray(tables) ? tables : tables.rows || [];
142
+ return rows.map((row) => row.table_name).filter((table) => !skipTables.includes(table));
88
143
  };
89
144
  exports.dbListTables = dbListTables;
90
145
  /**
91
- * Removes all the records from provided list of tables
92
- * @param tablesToClean array of table names
93
- * @param knexHandle Knex handle object with configured connection to DB
94
- * @param appSettings settings with db related information
95
- * @returns promise
146
+ * Deletes all records from the provided list of tables, one at a time.
147
+ * Order matters if foreign key constraints exist — pass tables in dependency order.
148
+ *
149
+ * @param tablesToClean Array of table names to clean
150
+ * @param knexHandle Knex instance with configured DB connection
151
+ * @param appSettings Settings object passed through to dbCleanTable
152
+ * @returns The list of cleaned table names
96
153
  */
97
154
  const dbClean = async (tablesToClean, knexHandle, appSettings) => {
98
- for (let idx = 0, len = tablesToClean.length; idx < len; ++idx) {
99
- await dbCleanTable(tablesToClean[idx], knexHandle, appSettings);
155
+ for (const table of tablesToClean) {
156
+ await dbCleanTable(table, knexHandle, appSettings);
100
157
  }
101
- return new bluebird_1.default((resolve) => {
102
- resolve(tablesToClean);
103
- });
158
+ // Fix: removed redundant `new BPromise(resolve => resolve(...))` wrapper —
159
+ // function is already async so returning directly is equivalent
160
+ return tablesToClean;
104
161
  };
105
162
  exports.dbClean = dbClean;
106
163
  /**
107
- * Selects all the tables in the schema and drops them.
108
- * This approach does not work in case we have constraints.
109
- * TODO: Remove all constraints and then drop tables.
164
+ * Drops all tables in the configured schema (or entire database if no schema set).
165
+ *
166
+ * WARNING: Destructive — permanently removes all tables and their data.
167
+ * Does not handle foreign key constraints — tables with dependencies may
168
+ * fail to drop. See TODO below.
169
+ *
170
+ * TODO: Remove all constraints before dropping tables to handle FK dependencies.
171
+ *
172
+ * @param knexHandle Knex instance with configured DB connection
173
+ * @param appSettings Settings object with dbType and optional dbSchema
110
174
  */
111
- const dbWipe = (knexHandle, appSettings) => {
112
- let query = SQLS[appSettings.dbType].dropTablesSchema(appSettings);
113
- if (!appSettings.dbSchema) {
114
- query = SQLS[appSettings.dbType].dropTables(appSettings);
175
+ const dbWipe = async (knexHandle, appSettings) => {
176
+ (0, exports.assertSupportedDbType)(appSettings.dbType);
177
+ const query = appSettings.dbSchema
178
+ ? SQLS[appSettings.dbType].dropTablesSchema(appSettings)
179
+ : SQLS[appSettings.dbType].dropTables(appSettings);
180
+ const result = await knexHandle.raw(query);
181
+ const commands = result.rows.map((r) => r.cmd);
182
+ // Fix: replaced BPromise.each() with for...of to remove bluebird dependency
183
+ // and align with async/await style used throughout the codebase
184
+ for (const cmd of commands) {
185
+ await knexHandle.raw(cmd);
115
186
  }
116
- return knexHandle
117
- .raw(query)
118
- .then((result) => result.rows.map((r) => r.cmd))
119
- .then((commands) => bluebird_1.default.each(commands, (cmd) => knexHandle.raw(cmd)));
120
187
  };
121
188
  exports.dbWipe = dbWipe;
122
189
  /**
123
- * Drop all tables, run migrations, then seed
190
+ * Drops all tables, runs all pending migrations, then optionally seeds the database.
191
+ * Intended for test environment reset between test suites.
192
+ *
193
+ * Fix: now re-throws after logging so callers know the reset failed rather
194
+ * than silently continuing with a broken database state.
195
+ *
196
+ * @param knexHandle Knex instance with configured DB connection
197
+ * @param appSettings Settings object passed through to dbWipe and dbRunMigrations
124
198
  */
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));
199
+ const dbReset = async (knexHandle, appSettings) => {
200
+ try {
201
+ await dbWipe(knexHandle, appSettings);
202
+ await dbRunMigrations(knexHandle, appSettings);
203
+ }
204
+ catch (ex) {
205
+ console.error('An exception has occurred on resetting database:', ex);
206
+ throw ex;
207
+ }
129
208
  };
130
209
  exports.dbReset = dbReset;
131
210
  /**
132
- * Go from array of objects which contain keys of object names which have an array value of seeded objects
133
- * to a single object with keys of object names and arrays of seeded objects
134
- * ie from [{table1: [], table2: [] }, { table3: [] }]
135
- * to { table1: [], table2: [], table3: []}
211
+ * Merges an array of seed result objects into a single flat object.
212
+ *
213
+ * Converts: `[{ table1: [...], table2: [...] }, { table3: [...] }]`
214
+ * Into: `{ table1: [...], table2: [...], table3: [...] }`
215
+ *
216
+ * Useful for collecting the results of multiple seed generators before
217
+ * inserting or asserting on them in tests.
218
+ *
219
+ * Fix: replaced `for...in` (which includes inherited properties) with
220
+ * `Object.assign()` which only copies own enumerable properties.
221
+ *
222
+ * @param generatedSeedArrays Array of seed result objects to merge
136
223
  */
137
- const dbTransformSeedsToObject = (generatedSeedArrays) => (0, lodash_1.reduce)(generatedSeedArrays, (acc, cur) => {
138
- for (const key in cur) {
139
- acc[key] = cur[key];
140
- }
141
- return acc;
142
- }, {});
224
+ const dbTransformSeedsToObject = (generatedSeedArrays) => (0, lodash_1.reduce)(generatedSeedArrays, (acc, cur) => Object.assign(acc, cur), {});
143
225
  exports.dbTransformSeedsToObject = dbTransformSeedsToObject;
144
- const dbRunMigrations = (knexHandle, appSettings) => {
145
- return knexHandle.migrate
146
- .latest()
147
- .then(async (result) => {
148
- if (appSettings && appSettings.runDbSeed && result[1].length > 0) {
149
- await knexHandle.seed.run();
150
- }
151
- console.log('Ran', result[1].length, 'migration(s)');
152
- return knexHandle.migrate.currentVersion();
153
- })
154
- .then((version) => console.log('Current version of database: ', version));
226
+ /**
227
+ * Runs all pending Knex migrations and optionally seeds the database.
228
+ * Seeds are only run if `appSettings.runDbSeed` is true AND at least one
229
+ * migration was applied — prevents re-seeding an already-seeded database.
230
+ *
231
+ * Logs the number of migrations run and the resulting schema version.
232
+ *
233
+ * @param knexHandle Knex instance with configured DB connection
234
+ * @param appSettings Settings object with optional runDbSeed flag
235
+ */
236
+ const dbRunMigrations = async (knexHandle, appSettings) => {
237
+ const result = await knexHandle.migrate.latest();
238
+ if (appSettings?.runDbSeed && result[1].length > 0) {
239
+ await knexHandle.seed.run();
240
+ }
241
+ console.info('Ran', result[1].length, 'migration(s)');
242
+ const version = await knexHandle.migrate.currentVersion();
243
+ console.info('Current version of database:', version);
155
244
  };
156
245
  exports.dbRunMigrations = dbRunMigrations;
@@ -1,2 +1,11 @@
1
- declare const dbSeed: (dirname: string, seedFiles: any, knexHandle: any, config: any) => Promise<any>;
1
+ /**
2
+ * Full seed pipeline: generate seeds from files, delete existing records,
3
+ * then insert the generated seeds.
4
+ *
5
+ * @param dirname Absolute directory path containing the `objects/` folder
6
+ * @param seedFiles Array of filename groups
7
+ * @param knexHandle Knex instance with configured DB connection
8
+ * @param config Config object with dbSchema and other db settings
9
+ */
10
+ declare const dbSeed: (dirname: string, seedFiles: string[][], knexHandle: any, config: any) => Promise<void>;
2
11
  export { dbSeed };
package/build/dbSeeder.js CHANGED
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/seedHelpers.ts
2
3
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
4
  if (k2 === undefined) k2 = k;
4
5
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -40,16 +41,46 @@ exports.dbSeed = void 0;
40
41
  const path_1 = __importDefault(require("path"));
41
42
  const lodash_1 = require("lodash");
42
43
  const dbHelpers_1 = require("./dbHelpers");
44
+ /**
45
+ * Seed utility functions for use outside of the DbMigratorAndSeeder class.
46
+ *
47
+ * Note: the logic in generateSeeds, removeSeedsFromDb, and insertRecords
48
+ * mirrors DbMigratorAndSeeder's instance methods of the same name.
49
+ * If you update the seeding logic here, keep DbMigratorAndSeeder in sync
50
+ * (or consolidate by having DbMigratorAndSeeder delegate to these functions).
51
+ */
52
+ /**
53
+ * Loads and executes seed generator functions from the provided file list,
54
+ * building a dependency-ordered array of seed groups.
55
+ *
56
+ * `seedFiles` is an array of groups (arrays of filenames). Within each group,
57
+ * seeds are generated sequentially and results of earlier seeds are available
58
+ * to later seeds via the `seeds` accumulator — allowing seeds to reference
59
+ * ids of previously generated records.
60
+ *
61
+ * Files are loaded from `dirname/objects/<filename>` without extension —
62
+ * the module resolver handles `.js`/`.ts` based on the runtime.
63
+ *
64
+ * Fix: removed hardcoded `.js` extension — was breaking in TypeScript/ESM.
65
+ *
66
+ * @param dirname Absolute directory path containing the `objects/` folder
67
+ * @param seedFiles Array of filename groups, e.g. `[['users'], ['posts', 'comments']]`
68
+ * @returns Array of seed group objects ready for `insertRecords()`
69
+ */
43
70
  const generateSeeds = async (dirname, seedFiles) => {
44
71
  let seedGroups = [];
45
72
  const seedFileNames = (0, lodash_1.flatten)(seedFiles);
46
- const seedFnExports = await Promise.all((0, lodash_1.map)(seedFileNames, (filename) => Promise.resolve(`${path_1.default.join(dirname, `./objects/${filename}.js`)}`).then(s => __importStar(require(s)))));
47
- const seedFns = (0, lodash_1.map)(seedFnExports, 'default');
73
+ // Load all seed modules in parallel
74
+ const seedFnExports = await Promise.all(
75
+ // Fix: removed hardcoded '.js' extension — let the module resolver handle it
76
+ seedFileNames.map((filename) => Promise.resolve(`${path_1.default.join(dirname, `./objects/${filename}`)}`).then(s => __importStar(require(s)))));
77
+ // Build a filename → default export map for O(1) lookup in the reduce below
48
78
  const seedFnsMap = {};
49
- for (let i = 0; i < seedFileNames.length; i++) {
50
- const seedFileName = seedFileNames[i];
51
- seedFnsMap[seedFileName] = seedFns[i];
52
- }
79
+ seedFileNames.forEach((filename, i) => {
80
+ seedFnsMap[filename] = seedFnExports[i].default;
81
+ });
82
+ // Process seed files group by group, carrying generated seeds forward
83
+ // so later seeds can reference ids from earlier ones
53
84
  seedFiles.reduce((seeds, fileGroup) => {
54
85
  seedGroups = seedGroups.concat(fileGroup.reduce((group, filename) => {
55
86
  const seedFn = seedFnsMap[filename];
@@ -62,22 +93,56 @@ const generateSeeds = async (dirname, seedFiles) => {
62
93
  }, {});
63
94
  return seedGroups;
64
95
  };
65
- const removeSeedsFromDb = (seedFiles, knexHandle, config) => {
96
+ /**
97
+ * Deletes all records for the tables referenced by `seedFiles`, in reverse
98
+ * order to respect foreign key dependencies (children before parents).
99
+ *
100
+ * @param seedFiles Array of filename groups — table order derived from
101
+ * the flattened + reversed list of filenames
102
+ * @param knexHandle Knex instance with configured DB connection
103
+ * @param config Config object passed through to dbClean
104
+ */
105
+ const removeSeedsFromDb = async (seedFiles, knexHandle, config) => {
66
106
  const tablesToReset = (0, lodash_1.flatten)(seedFiles).reverse();
67
- console.log('Deleting records from tables: ', tablesToReset);
107
+ console.info('Deleting records from tables:', tablesToReset);
68
108
  return (0, dbHelpers_1.dbClean)(tablesToReset, knexHandle, config);
69
109
  };
70
- const insertRecords = (seedGroups, knexHandle, config) => {
110
+ /**
111
+ * Inserts seed records group by group, in order.
112
+ * Groups are processed sequentially (each group waits for the previous)
113
+ * but records within a group are inserted in parallel via `Promise.all`.
114
+ *
115
+ * Sequential group processing preserves seed dependency order —
116
+ * a group that references records from a previous group can rely on
117
+ * those records being present before it runs.
118
+ *
119
+ * Fix: replaced async reduce anti-pattern with `for...of` + `await`
120
+ * for clarity — behaviour is identical (sequential groups, parallel within group).
121
+ * Fix: corrected log message typo ('tables tables' → 'into tables').
122
+ *
123
+ * @param seedGroups Array of seed group objects from `generateSeeds()`
124
+ * @param knexHandle Knex instance with configured DB connection
125
+ * @param config Config object with dbSchema
126
+ */
127
+ const insertRecords = async (seedGroups, knexHandle, config) => {
71
128
  const { dbSchema } = config || {};
72
- console.log('Inserting seeds records tables tables...');
73
- return seedGroups.reduce(async (previousGroup, group) => {
74
- await previousGroup;
75
- return Promise.all(Object.keys(group).map((table) => knexHandle(table).withSchema(dbSchema).insert(group[table])));
76
- }, Promise.resolve());
129
+ console.info('Inserting seed records into tables...');
130
+ for (const group of seedGroups) {
131
+ await Promise.all(Object.keys(group).map((table) => knexHandle(table).withSchema(dbSchema).insert(group[table])));
132
+ }
77
133
  };
134
+ /**
135
+ * Full seed pipeline: generate seeds from files, delete existing records,
136
+ * then insert the generated seeds.
137
+ *
138
+ * @param dirname Absolute directory path containing the `objects/` folder
139
+ * @param seedFiles Array of filename groups
140
+ * @param knexHandle Knex instance with configured DB connection
141
+ * @param config Config object with dbSchema and other db settings
142
+ */
78
143
  const dbSeed = async (dirname, seedFiles, knexHandle, config) => {
79
144
  const groups = await generateSeeds(dirname, seedFiles);
80
145
  await removeSeedsFromDb(seedFiles, knexHandle, config);
81
- return await insertRecords(groups, knexHandle, config);
146
+ await insertRecords(groups, knexHandle, config);
82
147
  };
83
148
  exports.dbSeed = dbSeed;
@@ -1,14 +1,131 @@
1
1
  import { DbFieldAddDefaultInterface } from './interfaces';
2
- import { FIELDS } from './constants';
2
+ /**
3
+ * Knex migration helper functions for adding standard column sets to tables.
4
+ *
5
+ * All functions accept a Knex `TableBuilder` instance as their first argument
6
+ * (`table: any` — typed as any to avoid coupling to a specific Knex version).
7
+ * They are intended to be called inside `knex.schema.createTable()` or
8
+ * `knex.schema.alterTable()` callbacks.
9
+ *
10
+ * Example usage in a migration:
11
+ * exports.up = (knex) =>
12
+ * knex.schema.createTable('post', (table) => {
13
+ * table.uuid('id').primary();
14
+ * table.text('title').notNullable();
15
+ * dbFieldAddDefaults(table, { addStatus: true, addUserInfo: true });
16
+ * });
17
+ */
18
+ /**
19
+ * Adds a standard set of default columns to a table.
20
+ *
21
+ * Columns added based on options:
22
+ * - `addStatus` → status (integer, indexed)
23
+ * - `addVersion` → version (integer)
24
+ * - `addUserInfo` → created_by, updated_by, removed_by (uuid)
25
+ * - `!skipTimestamps` → created_at, updated_at (via knex timestamps()),
26
+ * removed_at (dateTime, nullable),
27
+ * removed_at_str (string, indexed) unless skipRemovedAtStr
28
+ *
29
+ * Fix: `removed_at_str` index was added whenever `skipRemovedAtStr !== true`,
30
+ * regardless of `skipTimestamps`. If `skipTimestamps === true`, the column is
31
+ * never created but the index was still attempted — causing a migration error.
32
+ * Index is now only added when both `skipTimestamps` and `skipRemovedAtStr` are false.
33
+ *
34
+ * Note on `addUserInfo` + `removed_by`:
35
+ * `removed_by` is added whenever `addUserInfo` is true, even if the table
36
+ * uses hard deletes. On hard-delete tables this column exists but is never
37
+ * written — acceptable for schema consistency but worth noting.
38
+ *
39
+ * @param table Knex TableBuilder instance
40
+ * @param opt Column selection options
41
+ */
3
42
  export declare const dbFieldAddDefaults: (table: any, opt?: DbFieldAddDefaultInterface) => void;
43
+ /**
44
+ * Adds a text-based `order_no` column for lexicographic ordering.
45
+ * Uses string ordering — suitable for drag-and-drop reordering scenarios
46
+ * where records can be inserted between existing values without renumbering.
47
+ *
48
+ * Default value matches DEFAULT_ORDER_NO from constants ('10000000').
49
+ * Large starting value leaves room for manual insertions before the first
50
+ * auto-assigned record.
51
+ *
52
+ * @param table Knex TableBuilder instance
53
+ * @param opt Options: `addIndex` — whether to add an index on order_no
54
+ * @returns The Knex column chain for further modification
55
+ */
4
56
  export declare const addOrderNo: (table: any, opt?: any) => any;
57
+ /**
58
+ * Adds a decimal `order_no` column for numeric ordering.
59
+ * Uses a high-precision decimal (30, 15) to support fractional insertion
60
+ * between existing values.
61
+ *
62
+ * Note: default value (1000000) intentionally differs from addOrderNo's
63
+ * DEFAULT_ORDER_NO (10000000) — numeric sequences start lower since
64
+ * fractional values can be inserted between any two integers.
65
+ *
66
+ * @param table Knex TableBuilder instance
67
+ * @param opt Options: `addIndex` — whether to add an index on order_no
68
+ * @returns The Knex column chain for further modification
69
+ */
5
70
  export declare const addOrderNoNum: (table: any, opt?: any) => any;
71
+ /**
72
+ * Adds a high-precision decimal column for monetary or other precise amounts.
73
+ * Uses decimal(19, 4) — sufficient for most financial amounts up to
74
+ * 999,999,999,999,999 with 4 decimal places.
75
+ *
76
+ * @param table Knex TableBuilder instance
77
+ * @param fieldName Column name for the amount field
78
+ * @returns The Knex column chain for further modification
79
+ */
6
80
  export declare const addAmount: (table: any, fieldName: string) => any;
81
+ /**
82
+ * Adds a `space_id` string column (128 chars) with an optional foreign key
83
+ * to the `space` table.
84
+ *
85
+ * Typed as string(128) since space identifiers are strings, not UUIDs.
86
+ *
87
+ * @param table Knex TableBuilder instance
88
+ * @param opt Options: `addForeignKey` — whether to add FK to space table
89
+ * @returns The Knex column chain for further modification
90
+ */
7
91
  export declare const addSpaceId: (table: any, opt?: any) => any;
92
+ /**
93
+ * Adds a `user_id` UUID column with optional foreign key to the `user` table
94
+ * and optional index.
95
+ *
96
+ * @param table Knex TableBuilder instance
97
+ * @param opt Options: `addForeignKey`, `addIndex`
98
+ * @returns The Knex column chain for further modification
99
+ */
8
100
  export declare const addUserId: (table: any, opt?: any) => any;
101
+ /**
102
+ * Adds an `account_id` UUID column with optional foreign key to the `account`
103
+ * table and optional index.
104
+ *
105
+ * @param table Knex TableBuilder instance
106
+ * @param opt Options: `addForeignKey`, `addIndex`
107
+ * @returns The Knex column chain for further modification
108
+ */
9
109
  export declare const addAccountId: (table: any, opt?: any) => any;
110
+ /**
111
+ * Adds a `lang` text column defaulting to 'en' with optional foreign key
112
+ * to a `language` table and optional index.
113
+ *
114
+ * @param table Knex TableBuilder instance
115
+ * @param opt Options: `addForeignKey`, `addIndex`
116
+ * @returns The Knex column chain for further modification
117
+ */
10
118
  export declare const addLang: (table: any, opt?: any) => any;
11
- export declare const defaultFields: (opt?: any) => {
12
- [FIELDS.CREATED_AT]: string;
13
- [FIELDS.UPDATED_AT]: string;
14
- };
119
+ /**
120
+ * Returns a plain object with default field values for use in Knex seed files.
121
+ *
122
+ * Provides consistent baseline timestamps for seeded records.
123
+ * The hardcoded date ('2021-01-01T00:00:00Z') is intentional for seeds —
124
+ * using a static past date ensures seed data is reproducible and
125
+ * distinguishable from records created at runtime.
126
+ *
127
+ * @param opt Options: `addUserInfo` — whether to include created_by/updated_by
128
+ * UUID fields (set to UUID_EMPTY as placeholder values)
129
+ * @returns Plain object with default field values
130
+ */
131
+ export declare const defaultFields: (opt?: any) => Record<string, any>;