@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,8 +1,49 @@
1
1
  "use strict";
2
+ // ./src/dbFieldHelpers.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.defaultFields = exports.addLang = exports.addAccountId = exports.addUserId = exports.addSpaceId = exports.addAmount = exports.addOrderNoNum = exports.addOrderNo = exports.dbFieldAddDefaults = void 0;
4
5
  const utils_1 = require("@sdflc/utils");
5
6
  const constants_1 = require("./constants");
7
+ /**
8
+ * Knex migration helper functions for adding standard column sets to tables.
9
+ *
10
+ * All functions accept a Knex `TableBuilder` instance as their first argument
11
+ * (`table: any` — typed as any to avoid coupling to a specific Knex version).
12
+ * They are intended to be called inside `knex.schema.createTable()` or
13
+ * `knex.schema.alterTable()` callbacks.
14
+ *
15
+ * Example usage in a migration:
16
+ * exports.up = (knex) =>
17
+ * knex.schema.createTable('post', (table) => {
18
+ * table.uuid('id').primary();
19
+ * table.text('title').notNullable();
20
+ * dbFieldAddDefaults(table, { addStatus: true, addUserInfo: true });
21
+ * });
22
+ */
23
+ /**
24
+ * Adds a standard set of default columns to a table.
25
+ *
26
+ * Columns added based on options:
27
+ * - `addStatus` → status (integer, indexed)
28
+ * - `addVersion` → version (integer)
29
+ * - `addUserInfo` → created_by, updated_by, removed_by (uuid)
30
+ * - `!skipTimestamps` → created_at, updated_at (via knex timestamps()),
31
+ * removed_at (dateTime, nullable),
32
+ * removed_at_str (string, indexed) unless skipRemovedAtStr
33
+ *
34
+ * Fix: `removed_at_str` index was added whenever `skipRemovedAtStr !== true`,
35
+ * regardless of `skipTimestamps`. If `skipTimestamps === true`, the column is
36
+ * never created but the index was still attempted — causing a migration error.
37
+ * Index is now only added when both `skipTimestamps` and `skipRemovedAtStr` are false.
38
+ *
39
+ * Note on `addUserInfo` + `removed_by`:
40
+ * `removed_by` is added whenever `addUserInfo` is true, even if the table
41
+ * uses hard deletes. On hard-delete tables this column exists but is never
42
+ * written — acceptable for schema consistency but worth noting.
43
+ *
44
+ * @param table Knex TableBuilder instance
45
+ * @param opt Column selection options
46
+ */
6
47
  const dbFieldAddDefaults = (table, opt) => {
7
48
  const { addUserInfo, addVersion, addStatus, skipTimestamps, skipRemovedAtStr } = opt || {};
8
49
  if (addStatus) {
@@ -10,7 +51,8 @@ const dbFieldAddDefaults = (table, opt) => {
10
51
  .integer(constants_1.FIELDS.STATUS)
11
52
  .defaultTo(utils_1.STATUSES.ACTIVE)
12
53
  .comment(opt?.statusComment ||
13
- 'The field is used to specify record status: 50 - Test, 100 - Active, 200 - Draft, 300 - Pending, 1000 - Blocked, 5000 - Disabled, 10000 - Removed');
54
+ 'The field is used to specify record status: 50 - Test, 100 - Active, 200 - Draft, ' +
55
+ '300 - Pending, 1000 - Blocked, 5000 - Disabled, 10000 - Removed');
14
56
  }
15
57
  if (addVersion) {
16
58
  table
@@ -20,48 +62,108 @@ const dbFieldAddDefaults = (table, opt) => {
20
62
  }
21
63
  if (addUserInfo) {
22
64
  table.uuid(constants_1.FIELDS.CREATED_BY).comment('ID of user who created the record');
23
- table.uuid(constants_1.FIELDS.UPDATED_BY).comment('ID of the last user who update the record');
24
- table.uuid(constants_1.FIELDS.REMOVED_BY).comment('ID of user who removed the record');
65
+ table.uuid(constants_1.FIELDS.UPDATED_BY).comment('ID of the last user who updated the record');
66
+ table.uuid(constants_1.FIELDS.REMOVED_BY).comment('ID of user who soft-deleted the record');
25
67
  }
26
68
  if (skipTimestamps !== true) {
27
69
  table.timestamps(true, true);
28
70
  table
29
71
  .dateTime(constants_1.FIELDS.REMOVED_AT)
30
- .comment('Date and time of removal. As it is nullable it cannot be used in any unique index');
72
+ .comment('Date and time of removal. Nullable — cannot be used in unique indexes. ' +
73
+ 'Populated on soft-delete; null means record is active.');
31
74
  if (skipRemovedAtStr !== true) {
32
- table.string(constants_1.FIELDS.REMOVED_AT_STR, 32).defaultTo('').comment('Used to create unique indexes.');
75
+ table
76
+ .string(constants_1.FIELDS.REMOVED_AT_STR, 32)
77
+ .defaultTo('')
78
+ .comment('Formatted removal timestamp string. Used to build unique indexes that ' +
79
+ 'allow deleted records to be re-created with the same unique key.');
33
80
  }
34
81
  table.index([constants_1.FIELDS.CREATED_AT]);
35
82
  table.index([constants_1.FIELDS.UPDATED_AT]);
83
+ // Fix: was outside this block, causing index creation to be attempted
84
+ // even when removed_at_str column was never added (skipTimestamps === true)
85
+ if (skipRemovedAtStr !== true) {
86
+ table.index([constants_1.FIELDS.REMOVED_AT_STR]);
87
+ }
36
88
  }
37
89
  if (addStatus) {
38
90
  table.index([constants_1.FIELDS.STATUS]);
39
91
  }
40
- if (skipRemovedAtStr !== true) {
41
- table.index([constants_1.FIELDS.REMOVED_AT_STR]);
42
- }
43
92
  };
44
93
  exports.dbFieldAddDefaults = dbFieldAddDefaults;
94
+ /**
95
+ * Adds a text-based `order_no` column for lexicographic ordering.
96
+ * Uses string ordering — suitable for drag-and-drop reordering scenarios
97
+ * where records can be inserted between existing values without renumbering.
98
+ *
99
+ * Default value matches DEFAULT_ORDER_NO from constants ('10000000').
100
+ * Large starting value leaves room for manual insertions before the first
101
+ * auto-assigned record.
102
+ *
103
+ * @param table Knex TableBuilder instance
104
+ * @param opt Options: `addIndex` — whether to add an index on order_no
105
+ * @returns The Knex column chain for further modification
106
+ */
45
107
  const addOrderNo = (table, opt) => {
46
- const chain = table.text(constants_1.FIELDS.ORDER_NO).notNullable().defaultTo('10000000');
108
+ const chain = table
109
+ .text(constants_1.FIELDS.ORDER_NO)
110
+ .notNullable()
111
+ .defaultTo(constants_1.DEFAULT_ORDER_NO)
112
+ .comment('Lexicographic display order. Use addOrderNoNum for numeric ordering.');
47
113
  if (opt?.addIndex === true) {
48
114
  table.index([constants_1.FIELDS.ORDER_NO]);
49
115
  }
50
116
  return chain;
51
117
  };
52
118
  exports.addOrderNo = addOrderNo;
119
+ /**
120
+ * Adds a decimal `order_no` column for numeric ordering.
121
+ * Uses a high-precision decimal (30, 15) to support fractional insertion
122
+ * between existing values.
123
+ *
124
+ * Note: default value (1000000) intentionally differs from addOrderNo's
125
+ * DEFAULT_ORDER_NO (10000000) — numeric sequences start lower since
126
+ * fractional values can be inserted between any two integers.
127
+ *
128
+ * @param table Knex TableBuilder instance
129
+ * @param opt Options: `addIndex` — whether to add an index on order_no
130
+ * @returns The Knex column chain for further modification
131
+ */
53
132
  const addOrderNoNum = (table, opt) => {
54
- const chain = table.decimal(constants_1.FIELDS.ORDER_NO, 30, 15).notNullable().defaultTo(1000000).comment('Display order');
133
+ const chain = table
134
+ .decimal(constants_1.FIELDS.ORDER_NO, 30, 15)
135
+ .notNullable()
136
+ .defaultTo(1000000)
137
+ .comment('Numeric display order. Use addOrderNo for lexicographic ordering.');
55
138
  if (opt?.addIndex === true) {
56
139
  table.index([constants_1.FIELDS.ORDER_NO]);
57
140
  }
58
141
  return chain;
59
142
  };
60
143
  exports.addOrderNoNum = addOrderNoNum;
144
+ /**
145
+ * Adds a high-precision decimal column for monetary or other precise amounts.
146
+ * Uses decimal(19, 4) — sufficient for most financial amounts up to
147
+ * 999,999,999,999,999 with 4 decimal places.
148
+ *
149
+ * @param table Knex TableBuilder instance
150
+ * @param fieldName Column name for the amount field
151
+ * @returns The Knex column chain for further modification
152
+ */
61
153
  const addAmount = (table, fieldName) => {
62
154
  return table.decimal(fieldName, 19, 4);
63
155
  };
64
156
  exports.addAmount = addAmount;
157
+ /**
158
+ * Adds a `space_id` string column (128 chars) with an optional foreign key
159
+ * to the `space` table.
160
+ *
161
+ * Typed as string(128) since space identifiers are strings, not UUIDs.
162
+ *
163
+ * @param table Knex TableBuilder instance
164
+ * @param opt Options: `addForeignKey` — whether to add FK to space table
165
+ * @returns The Knex column chain for further modification
166
+ */
65
167
  const addSpaceId = (table, opt) => {
66
168
  const chain = table.string(constants_1.FIELDS.SPACE_ID, 128).notNullable().comment('Reference to the space table');
67
169
  if (opt?.addForeignKey === true) {
@@ -70,6 +172,14 @@ const addSpaceId = (table, opt) => {
70
172
  return chain;
71
173
  };
72
174
  exports.addSpaceId = addSpaceId;
175
+ /**
176
+ * Adds a `user_id` UUID column with optional foreign key to the `user` table
177
+ * and optional index.
178
+ *
179
+ * @param table Knex TableBuilder instance
180
+ * @param opt Options: `addForeignKey`, `addIndex`
181
+ * @returns The Knex column chain for further modification
182
+ */
73
183
  const addUserId = (table, opt) => {
74
184
  const chain = table.uuid(constants_1.FIELDS.USER_ID).notNullable().comment('Reference to the user table');
75
185
  if (opt?.addForeignKey === true) {
@@ -81,6 +191,14 @@ const addUserId = (table, opt) => {
81
191
  return chain;
82
192
  };
83
193
  exports.addUserId = addUserId;
194
+ /**
195
+ * Adds an `account_id` UUID column with optional foreign key to the `account`
196
+ * table and optional index.
197
+ *
198
+ * @param table Knex TableBuilder instance
199
+ * @param opt Options: `addForeignKey`, `addIndex`
200
+ * @returns The Knex column chain for further modification
201
+ */
84
202
  const addAccountId = (table, opt) => {
85
203
  const chain = table.uuid(constants_1.FIELDS.ACCOUNT_ID).notNullable().comment('Reference to the account table');
86
204
  if (opt?.addForeignKey === true) {
@@ -92,8 +210,16 @@ const addAccountId = (table, opt) => {
92
210
  return chain;
93
211
  };
94
212
  exports.addAccountId = addAccountId;
213
+ /**
214
+ * Adds a `lang` text column defaulting to 'en' with optional foreign key
215
+ * to a `language` table and optional index.
216
+ *
217
+ * @param table Knex TableBuilder instance
218
+ * @param opt Options: `addForeignKey`, `addIndex`
219
+ * @returns The Knex column chain for further modification
220
+ */
95
221
  const addLang = (table, opt) => {
96
- const chain = table.text(constants_1.FIELDS.LANG).defaultTo('en').notNullable().comment('Language, example: en, ru, en_CA, etc');
222
+ const chain = table.text(constants_1.FIELDS.LANG).defaultTo('en').notNullable().comment('Language code, e.g. en, ru, en_CA');
97
223
  if (opt?.addForeignKey === true) {
98
224
  table.foreign(constants_1.FIELDS.LANG).references(`language.${constants_1.FIELDS.ID}`).onUpdate('CASCADE').onDelete('CASCADE');
99
225
  }
@@ -103,11 +229,23 @@ const addLang = (table, opt) => {
103
229
  return chain;
104
230
  };
105
231
  exports.addLang = addLang;
232
+ /**
233
+ * Returns a plain object with default field values for use in Knex seed files.
234
+ *
235
+ * Provides consistent baseline timestamps for seeded records.
236
+ * The hardcoded date ('2021-01-01T00:00:00Z') is intentional for seeds —
237
+ * using a static past date ensures seed data is reproducible and
238
+ * distinguishable from records created at runtime.
239
+ *
240
+ * @param opt Options: `addUserInfo` — whether to include created_by/updated_by
241
+ * UUID fields (set to UUID_EMPTY as placeholder values)
242
+ * @returns Plain object with default field values
243
+ */
106
244
  const defaultFields = (opt) => {
107
245
  const { addUserInfo } = opt || {};
108
246
  const obj = {
109
- [constants_1.FIELDS.CREATED_AT]: '2021-01-01T00:00:00Z', // dh.dbUtcNow(),
110
- [constants_1.FIELDS.UPDATED_AT]: '2021-01-01T00:00:00Z', // dh.dbUtcNow(),
247
+ [constants_1.FIELDS.CREATED_AT]: '2021-01-01T00:00:00Z',
248
+ [constants_1.FIELDS.UPDATED_AT]: '2021-01-01T00:00:00Z',
111
249
  };
112
250
  if (addUserInfo === true) {
113
251
  obj[constants_1.FIELDS.CREATED_BY] = utils_1.UUID_EMPTY;
@@ -1,2 +1,25 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
1
2
  import { DownloadFileArgs } from './interfaces';
2
- export declare const downloadFile: (args: DownloadFileArgs) => Promise<any>;
3
+ /**
4
+ * Downloads a file from a URL to the local filesystem (or a provided writable stream).
5
+ *
6
+ * Uses axios with `responseType: 'stream'` and Node's stream pipeline for
7
+ * memory-efficient transfer of large files — data is piped directly to disk
8
+ * without buffering the entire response in memory.
9
+ *
10
+ * Returns an OpResult containing:
11
+ * - `url` — the resolved URL string
12
+ * - `fileName` — the resolved file name
13
+ * - `fullPathName`— the absolute path where the file was written
14
+ * - `size` — file size in bytes (from Content-Length header)
15
+ * - `mimeType` — MIME type from Content-Type header
16
+ * - `encoding` — charset from Content-Type header (e.g. 'utf-8'), if present
17
+ * - `speed` — download speed in bytes/second
18
+ * - `durationMs` — total download duration in milliseconds
19
+ *
20
+ * On failure, returns a failed OpResult with the error message and available
21
+ * file metadata (url, fileName, fullPathName, size: 0, mimeType: '').
22
+ *
23
+ * @param args DownloadFileArgs with url, optional fileName, folder, and stream
24
+ */
25
+ export declare const downloadFile: (args: DownloadFileArgs) => Promise<OpResult>;
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/downloadFile.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
@@ -19,24 +20,52 @@ const MESSAGES = {
19
20
  NO_FILENAME: 'Failed to download file as "fileName" prop was not provided and no file name was in the "url"',
20
21
  };
21
22
  const CHARSET = 'charset=';
23
+ /**
24
+ * Downloads a file from a URL to the local filesystem (or a provided writable stream).
25
+ *
26
+ * Uses axios with `responseType: 'stream'` and Node's stream pipeline for
27
+ * memory-efficient transfer of large files — data is piped directly to disk
28
+ * without buffering the entire response in memory.
29
+ *
30
+ * Returns an OpResult containing:
31
+ * - `url` — the resolved URL string
32
+ * - `fileName` — the resolved file name
33
+ * - `fullPathName`— the absolute path where the file was written
34
+ * - `size` — file size in bytes (from Content-Length header)
35
+ * - `mimeType` — MIME type from Content-Type header
36
+ * - `encoding` — charset from Content-Type header (e.g. 'utf-8'), if present
37
+ * - `speed` — download speed in bytes/second
38
+ * - `durationMs` — total download duration in milliseconds
39
+ *
40
+ * On failure, returns a failed OpResult with the error message and available
41
+ * file metadata (url, fileName, fullPathName, size: 0, mimeType: '').
42
+ *
43
+ * @param args DownloadFileArgs with url, optional fileName, folder, and stream
44
+ */
22
45
  const downloadFile = async (args) => {
23
46
  const measureTool = new utils_1.MeasureTool();
24
47
  const { durationMs, result } = await measureTool.measureExecTime('', async () => {
25
48
  if (!args?.url) {
26
49
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, {}, MESSAGES.NO_URL);
27
50
  }
28
- const url = new url_1.URL(args?.url);
29
- const fileName = !args?.fileName ? url.pathname.split('/').pop() || `${url.hostname}.html` : args?.fileName || '';
51
+ const url = new url_1.URL(args.url);
52
+ // Resolve fileName: use provided name, fall back to the last path segment
53
+ // of the URL, then fall back to hostname + .html for root URLs
54
+ const fileName = args?.fileName || url.pathname.split('/').pop() || `${url.hostname}.html`;
30
55
  if (!fileName) {
31
56
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, {}, MESSAGES.NO_FILENAME);
32
57
  }
33
- const fullPathName = path_1.default.resolve(args?.folder || '', fileName);
58
+ // Resolve to an absolute path. Falls back to process.cwd() when no
59
+ // folder is provided — makes the fallback behaviour explicit.
60
+ const fullPathName = path_1.default.resolve(args?.folder || process.cwd(), fileName);
34
61
  try {
35
62
  const response = await axios_1.default.get(url.toString(), {
36
63
  responseType: 'stream',
37
64
  });
38
- const strease2use = args?.stream || fs_1.default.createWriteStream(fullPathName);
39
- await pipeline(response.data, strease2use);
65
+ // Use a caller-provided writable stream if given (e.g. for in-memory
66
+ // or cloud storage targets), otherwise write to the local filesystem
67
+ const streamToUse = args?.stream || fs_1.default.createWriteStream(fullPathName);
68
+ await pipeline(response.data, streamToUse);
40
69
  const contentType = response?.headers?.[constants_1.HEADERS.CONTENT_TYPE] || '';
41
70
  const [mimeType, charset] = contentType.split('; ');
42
71
  const encoding = charset?.startsWith(CHARSET) ? charset.slice(CHARSET.length) : '';
@@ -50,24 +79,25 @@ const downloadFile = async (args) => {
50
79
  });
51
80
  }
52
81
  catch (ex) {
53
- return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, { url: url.toString(), fileName, fullPathName, size: 0, mimeType: '' }, ex.message);
82
+ // Include HTTP status code in the message when available (axios throws
83
+ // for 4xx/5xx responses with ex.response.status populated)
84
+ const statusCode = ex?.response?.status;
85
+ const message = statusCode ? `HTTP ${statusCode}: ${ex.message}` : ex.message;
86
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, { url: url.toString(), fileName, fullPathName, size: 0, mimeType: '' }, message);
54
87
  }
55
88
  });
56
- const data = result.getDataFirst();
57
- result.setData({ ...data, speed: (data.size * 1000) / durationMs, durationMs });
89
+ // Only enrich the result with speed/duration when the download succeeded —
90
+ // a failed result has no size to calculate speed from, and spreading null
91
+ // data would throw TypeError
92
+ if (result.didSucceed()) {
93
+ const data = result.getDataFirst() ?? {};
94
+ result.setData({
95
+ ...data,
96
+ // Guard against zero duration (e.g. cached response or measurement anomaly)
97
+ speed: durationMs > 0 ? (data.size * 1000) / durationMs : 0,
98
+ durationMs,
99
+ });
100
+ }
58
101
  return result;
59
102
  };
60
103
  exports.downloadFile = downloadFile;
61
- // const run = async () => {
62
- // // const result = await downloadFile({
63
- // // url: 'https://sushitei.com/wp-content/uploads/2022/08/2022-Sushi-Tei-Autumn-Menu.pdf',
64
- // // fileName: '',
65
- // // });
66
- // const result = await downloadFile({
67
- // url: 'https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v6.15/windows/pgadmin4-6.15-x64.exe',
68
- // fileName: '',
69
- // folder: path.resolve('d:\\Users\\dcerge\\Downloads'),
70
- // });
71
- // console.log('result', JSON.stringify(result, null, 2));
72
- // };
73
- // run();
@@ -0,0 +1,20 @@
1
+ import { Logger } from '@sdflc/utils';
2
+ import { BaseControllerPropsInterface } from './interfaces';
3
+ type OnResponseFn = (req: any, res: any, next: any) => Promise<void> | void;
4
+ /**
5
+ * Base class for REST API controllers.
6
+ */
7
+ declare class BaseController {
8
+ protected onResponse: OnResponseFn;
9
+ protected logger: Logger;
10
+ constructor(props?: BaseControllerPropsInterface);
11
+ init(_props?: any): void;
12
+ /**
13
+ * Wraps a controller method in consistent HTTP response handling.
14
+ * Supports OpResult, redirects, plain objects, and empty responses.
15
+ * @param method - Async handler receiving (req, res, next)
16
+ * @returns Express-compatible middleware function
17
+ */
18
+ json(method: (req: any, res: any, next: any) => Promise<any>): (req: any, res: any, next: any) => Promise<void>;
19
+ }
20
+ export { BaseController };
@@ -0,0 +1,58 @@
1
+ // ./src/baseController.ts
2
+ import check from 'check-types';
3
+ import { isOpResult } from '@sdflc/api-helpers';
4
+ import { isLogger, Logger, LoggerLevels } from '@sdflc/utils';
5
+ /**
6
+ * Base class for REST API controllers.
7
+ */
8
+ class BaseController {
9
+ onResponse;
10
+ logger;
11
+ constructor(props) {
12
+ this.onResponse = check.function(props?.onResponse)
13
+ ? props.onResponse
14
+ : async (_req, _res, _next) => {
15
+ /* no-op */
16
+ };
17
+ this.logger = props?.logger && isLogger(props.logger) ? props.logger : new Logger({ level: LoggerLevels.ERROR });
18
+ }
19
+ init(_props) {
20
+ // Implemented by subclasses to register routes on the Express app.
21
+ // Example:
22
+ // app.post(`${root}/event-webhook`, this.json(this.eventWebhook));
23
+ }
24
+ /**
25
+ * Wraps a controller method in consistent HTTP response handling.
26
+ * Supports OpResult, redirects, plain objects, and empty responses.
27
+ * @param method - Async handler receiving (req, res, next)
28
+ * @returns Express-compatible middleware function
29
+ */
30
+ json(method) {
31
+ return async (req, res, next) => {
32
+ try {
33
+ const result = await method(req, res, next);
34
+ if (isOpResult(result)) {
35
+ res.status(result.getHttpStatus()).json(result.toJS());
36
+ }
37
+ else if (result?.redirectUrl) {
38
+ // Do NOT call next() after redirect — response is already finalised
39
+ res.redirect(result.redirectUrl);
40
+ return;
41
+ }
42
+ else if (result) {
43
+ res.status(200).json(result);
44
+ }
45
+ else {
46
+ // 204 No Content — no body should be sent
47
+ res.status(204).end();
48
+ }
49
+ await this.onResponse(req, res, next);
50
+ }
51
+ catch (ex) {
52
+ this.logger.log(`An exception occurred processing '${req.method} ${req.originalUrl}'`);
53
+ next(ex);
54
+ }
55
+ };
56
+ }
57
+ }
58
+ export { BaseController };