@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,5 +1,46 @@
1
+ // ./src/dbFieldHelpers.ts
1
2
  import { STATUSES, UUID_EMPTY } from '@sdflc/utils';
2
- import { FIELDS } from './constants';
3
+ import { DEFAULT_ORDER_NO, FIELDS } from './constants';
4
+ /**
5
+ * Knex migration helper functions for adding standard column sets to tables.
6
+ *
7
+ * All functions accept a Knex `TableBuilder` instance as their first argument
8
+ * (`table: any` — typed as any to avoid coupling to a specific Knex version).
9
+ * They are intended to be called inside `knex.schema.createTable()` or
10
+ * `knex.schema.alterTable()` callbacks.
11
+ *
12
+ * Example usage in a migration:
13
+ * exports.up = (knex) =>
14
+ * knex.schema.createTable('post', (table) => {
15
+ * table.uuid('id').primary();
16
+ * table.text('title').notNullable();
17
+ * dbFieldAddDefaults(table, { addStatus: true, addUserInfo: true });
18
+ * });
19
+ */
20
+ /**
21
+ * Adds a standard set of default columns to a table.
22
+ *
23
+ * Columns added based on options:
24
+ * - `addStatus` → status (integer, indexed)
25
+ * - `addVersion` → version (integer)
26
+ * - `addUserInfo` → created_by, updated_by, removed_by (uuid)
27
+ * - `!skipTimestamps` → created_at, updated_at (via knex timestamps()),
28
+ * removed_at (dateTime, nullable),
29
+ * removed_at_str (string, indexed) unless skipRemovedAtStr
30
+ *
31
+ * Fix: `removed_at_str` index was added whenever `skipRemovedAtStr !== true`,
32
+ * regardless of `skipTimestamps`. If `skipTimestamps === true`, the column is
33
+ * never created but the index was still attempted — causing a migration error.
34
+ * Index is now only added when both `skipTimestamps` and `skipRemovedAtStr` are false.
35
+ *
36
+ * Note on `addUserInfo` + `removed_by`:
37
+ * `removed_by` is added whenever `addUserInfo` is true, even if the table
38
+ * uses hard deletes. On hard-delete tables this column exists but is never
39
+ * written — acceptable for schema consistency but worth noting.
40
+ *
41
+ * @param table Knex TableBuilder instance
42
+ * @param opt Column selection options
43
+ */
3
44
  export const dbFieldAddDefaults = (table, opt) => {
4
45
  const { addUserInfo, addVersion, addStatus, skipTimestamps, skipRemovedAtStr } = opt || {};
5
46
  if (addStatus) {
@@ -7,7 +48,8 @@ export const dbFieldAddDefaults = (table, opt) => {
7
48
  .integer(FIELDS.STATUS)
8
49
  .defaultTo(STATUSES.ACTIVE)
9
50
  .comment(opt?.statusComment ||
10
- 'The field is used to specify record status: 50 - Test, 100 - Active, 200 - Draft, 300 - Pending, 1000 - Blocked, 5000 - Disabled, 10000 - Removed');
51
+ 'The field is used to specify record status: 50 - Test, 100 - Active, 200 - Draft, ' +
52
+ '300 - Pending, 1000 - Blocked, 5000 - Disabled, 10000 - Removed');
11
53
  }
12
54
  if (addVersion) {
13
55
  table
@@ -17,44 +59,104 @@ export const dbFieldAddDefaults = (table, opt) => {
17
59
  }
18
60
  if (addUserInfo) {
19
61
  table.uuid(FIELDS.CREATED_BY).comment('ID of user who created the record');
20
- table.uuid(FIELDS.UPDATED_BY).comment('ID of the last user who update the record');
21
- table.uuid(FIELDS.REMOVED_BY).comment('ID of user who removed the record');
62
+ table.uuid(FIELDS.UPDATED_BY).comment('ID of the last user who updated the record');
63
+ table.uuid(FIELDS.REMOVED_BY).comment('ID of user who soft-deleted the record');
22
64
  }
23
65
  if (skipTimestamps !== true) {
24
66
  table.timestamps(true, true);
25
67
  table
26
68
  .dateTime(FIELDS.REMOVED_AT)
27
- .comment('Date and time of removal. As it is nullable it cannot be used in any unique index');
69
+ .comment('Date and time of removal. Nullable — cannot be used in unique indexes. ' +
70
+ 'Populated on soft-delete; null means record is active.');
28
71
  if (skipRemovedAtStr !== true) {
29
- table.string(FIELDS.REMOVED_AT_STR, 32).defaultTo('').comment('Used to create unique indexes.');
72
+ table
73
+ .string(FIELDS.REMOVED_AT_STR, 32)
74
+ .defaultTo('')
75
+ .comment('Formatted removal timestamp string. Used to build unique indexes that ' +
76
+ 'allow deleted records to be re-created with the same unique key.');
30
77
  }
31
78
  table.index([FIELDS.CREATED_AT]);
32
79
  table.index([FIELDS.UPDATED_AT]);
80
+ // Fix: was outside this block, causing index creation to be attempted
81
+ // even when removed_at_str column was never added (skipTimestamps === true)
82
+ if (skipRemovedAtStr !== true) {
83
+ table.index([FIELDS.REMOVED_AT_STR]);
84
+ }
33
85
  }
34
86
  if (addStatus) {
35
87
  table.index([FIELDS.STATUS]);
36
88
  }
37
- if (skipRemovedAtStr !== true) {
38
- table.index([FIELDS.REMOVED_AT_STR]);
39
- }
40
89
  };
90
+ /**
91
+ * Adds a text-based `order_no` column for lexicographic ordering.
92
+ * Uses string ordering — suitable for drag-and-drop reordering scenarios
93
+ * where records can be inserted between existing values without renumbering.
94
+ *
95
+ * Default value matches DEFAULT_ORDER_NO from constants ('10000000').
96
+ * Large starting value leaves room for manual insertions before the first
97
+ * auto-assigned record.
98
+ *
99
+ * @param table Knex TableBuilder instance
100
+ * @param opt Options: `addIndex` — whether to add an index on order_no
101
+ * @returns The Knex column chain for further modification
102
+ */
41
103
  export const addOrderNo = (table, opt) => {
42
- const chain = table.text(FIELDS.ORDER_NO).notNullable().defaultTo('10000000');
104
+ const chain = table
105
+ .text(FIELDS.ORDER_NO)
106
+ .notNullable()
107
+ .defaultTo(DEFAULT_ORDER_NO)
108
+ .comment('Lexicographic display order. Use addOrderNoNum for numeric ordering.');
43
109
  if (opt?.addIndex === true) {
44
110
  table.index([FIELDS.ORDER_NO]);
45
111
  }
46
112
  return chain;
47
113
  };
114
+ /**
115
+ * Adds a decimal `order_no` column for numeric ordering.
116
+ * Uses a high-precision decimal (30, 15) to support fractional insertion
117
+ * between existing values.
118
+ *
119
+ * Note: default value (1000000) intentionally differs from addOrderNo's
120
+ * DEFAULT_ORDER_NO (10000000) — numeric sequences start lower since
121
+ * fractional values can be inserted between any two integers.
122
+ *
123
+ * @param table Knex TableBuilder instance
124
+ * @param opt Options: `addIndex` — whether to add an index on order_no
125
+ * @returns The Knex column chain for further modification
126
+ */
48
127
  export const addOrderNoNum = (table, opt) => {
49
- const chain = table.decimal(FIELDS.ORDER_NO, 30, 15).notNullable().defaultTo(1000000).comment('Display order');
128
+ const chain = table
129
+ .decimal(FIELDS.ORDER_NO, 30, 15)
130
+ .notNullable()
131
+ .defaultTo(1000000)
132
+ .comment('Numeric display order. Use addOrderNo for lexicographic ordering.');
50
133
  if (opt?.addIndex === true) {
51
134
  table.index([FIELDS.ORDER_NO]);
52
135
  }
53
136
  return chain;
54
137
  };
138
+ /**
139
+ * Adds a high-precision decimal column for monetary or other precise amounts.
140
+ * Uses decimal(19, 4) — sufficient for most financial amounts up to
141
+ * 999,999,999,999,999 with 4 decimal places.
142
+ *
143
+ * @param table Knex TableBuilder instance
144
+ * @param fieldName Column name for the amount field
145
+ * @returns The Knex column chain for further modification
146
+ */
55
147
  export const addAmount = (table, fieldName) => {
56
148
  return table.decimal(fieldName, 19, 4);
57
149
  };
150
+ /**
151
+ * Adds a `space_id` string column (128 chars) with an optional foreign key
152
+ * to the `space` table.
153
+ *
154
+ * Typed as string(128) since space identifiers are strings, not UUIDs.
155
+ *
156
+ * @param table Knex TableBuilder instance
157
+ * @param opt Options: `addForeignKey` — whether to add FK to space table
158
+ * @returns The Knex column chain for further modification
159
+ */
58
160
  export const addSpaceId = (table, opt) => {
59
161
  const chain = table.string(FIELDS.SPACE_ID, 128).notNullable().comment('Reference to the space table');
60
162
  if (opt?.addForeignKey === true) {
@@ -62,6 +164,14 @@ export const addSpaceId = (table, opt) => {
62
164
  }
63
165
  return chain;
64
166
  };
167
+ /**
168
+ * Adds a `user_id` UUID column with optional foreign key to the `user` table
169
+ * and optional index.
170
+ *
171
+ * @param table Knex TableBuilder instance
172
+ * @param opt Options: `addForeignKey`, `addIndex`
173
+ * @returns The Knex column chain for further modification
174
+ */
65
175
  export const addUserId = (table, opt) => {
66
176
  const chain = table.uuid(FIELDS.USER_ID).notNullable().comment('Reference to the user table');
67
177
  if (opt?.addForeignKey === true) {
@@ -72,6 +182,14 @@ export const addUserId = (table, opt) => {
72
182
  }
73
183
  return chain;
74
184
  };
185
+ /**
186
+ * Adds an `account_id` UUID column with optional foreign key to the `account`
187
+ * table and optional index.
188
+ *
189
+ * @param table Knex TableBuilder instance
190
+ * @param opt Options: `addForeignKey`, `addIndex`
191
+ * @returns The Knex column chain for further modification
192
+ */
75
193
  export const addAccountId = (table, opt) => {
76
194
  const chain = table.uuid(FIELDS.ACCOUNT_ID).notNullable().comment('Reference to the account table');
77
195
  if (opt?.addForeignKey === true) {
@@ -82,8 +200,16 @@ export const addAccountId = (table, opt) => {
82
200
  }
83
201
  return chain;
84
202
  };
203
+ /**
204
+ * Adds a `lang` text column defaulting to 'en' with optional foreign key
205
+ * to a `language` table and optional index.
206
+ *
207
+ * @param table Knex TableBuilder instance
208
+ * @param opt Options: `addForeignKey`, `addIndex`
209
+ * @returns The Knex column chain for further modification
210
+ */
85
211
  export const addLang = (table, opt) => {
86
- const chain = table.text(FIELDS.LANG).defaultTo('en').notNullable().comment('Language, example: en, ru, en_CA, etc');
212
+ const chain = table.text(FIELDS.LANG).defaultTo('en').notNullable().comment('Language code, e.g. en, ru, en_CA');
87
213
  if (opt?.addForeignKey === true) {
88
214
  table.foreign(FIELDS.LANG).references(`language.${FIELDS.ID}`).onUpdate('CASCADE').onDelete('CASCADE');
89
215
  }
@@ -92,11 +218,23 @@ export const addLang = (table, opt) => {
92
218
  }
93
219
  return chain;
94
220
  };
221
+ /**
222
+ * Returns a plain object with default field values for use in Knex seed files.
223
+ *
224
+ * Provides consistent baseline timestamps for seeded records.
225
+ * The hardcoded date ('2021-01-01T00:00:00Z') is intentional for seeds —
226
+ * using a static past date ensures seed data is reproducible and
227
+ * distinguishable from records created at runtime.
228
+ *
229
+ * @param opt Options: `addUserInfo` — whether to include created_by/updated_by
230
+ * UUID fields (set to UUID_EMPTY as placeholder values)
231
+ * @returns Plain object with default field values
232
+ */
95
233
  export const defaultFields = (opt) => {
96
234
  const { addUserInfo } = opt || {};
97
235
  const obj = {
98
- [FIELDS.CREATED_AT]: '2021-01-01T00:00:00Z', // dh.dbUtcNow(),
99
- [FIELDS.UPDATED_AT]: '2021-01-01T00:00:00Z', // dh.dbUtcNow(),
236
+ [FIELDS.CREATED_AT]: '2021-01-01T00:00:00Z',
237
+ [FIELDS.UPDATED_AT]: '2021-01-01T00:00:00Z',
100
238
  };
101
239
  if (addUserInfo === true) {
102
240
  obj[FIELDS.CREATED_BY] = 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,3 +1,4 @@
1
+ // ./src/downloadFile.ts
1
2
  import util from 'util';
2
3
  import fs from 'fs';
3
4
  import stream from 'stream';
@@ -13,24 +14,52 @@ const MESSAGES = {
13
14
  NO_FILENAME: 'Failed to download file as "fileName" prop was not provided and no file name was in the "url"',
14
15
  };
15
16
  const CHARSET = 'charset=';
17
+ /**
18
+ * Downloads a file from a URL to the local filesystem (or a provided writable stream).
19
+ *
20
+ * Uses axios with `responseType: 'stream'` and Node's stream pipeline for
21
+ * memory-efficient transfer of large files — data is piped directly to disk
22
+ * without buffering the entire response in memory.
23
+ *
24
+ * Returns an OpResult containing:
25
+ * - `url` — the resolved URL string
26
+ * - `fileName` — the resolved file name
27
+ * - `fullPathName`— the absolute path where the file was written
28
+ * - `size` — file size in bytes (from Content-Length header)
29
+ * - `mimeType` — MIME type from Content-Type header
30
+ * - `encoding` — charset from Content-Type header (e.g. 'utf-8'), if present
31
+ * - `speed` — download speed in bytes/second
32
+ * - `durationMs` — total download duration in milliseconds
33
+ *
34
+ * On failure, returns a failed OpResult with the error message and available
35
+ * file metadata (url, fileName, fullPathName, size: 0, mimeType: '').
36
+ *
37
+ * @param args DownloadFileArgs with url, optional fileName, folder, and stream
38
+ */
16
39
  export const downloadFile = async (args) => {
17
40
  const measureTool = new MeasureTool();
18
41
  const { durationMs, result } = await measureTool.measureExecTime('', async () => {
19
42
  if (!args?.url) {
20
43
  return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, {}, MESSAGES.NO_URL);
21
44
  }
22
- const url = new URL(args?.url);
23
- const fileName = !args?.fileName ? url.pathname.split('/').pop() || `${url.hostname}.html` : args?.fileName || '';
45
+ const url = new URL(args.url);
46
+ // Resolve fileName: use provided name, fall back to the last path segment
47
+ // of the URL, then fall back to hostname + .html for root URLs
48
+ const fileName = args?.fileName || url.pathname.split('/').pop() || `${url.hostname}.html`;
24
49
  if (!fileName) {
25
50
  return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, {}, MESSAGES.NO_FILENAME);
26
51
  }
27
- const fullPathName = path.resolve(args?.folder || '', fileName);
52
+ // Resolve to an absolute path. Falls back to process.cwd() when no
53
+ // folder is provided — makes the fallback behaviour explicit.
54
+ const fullPathName = path.resolve(args?.folder || process.cwd(), fileName);
28
55
  try {
29
56
  const response = await axios.get(url.toString(), {
30
57
  responseType: 'stream',
31
58
  });
32
- const strease2use = args?.stream || fs.createWriteStream(fullPathName);
33
- await pipeline(response.data, strease2use);
59
+ // Use a caller-provided writable stream if given (e.g. for in-memory
60
+ // or cloud storage targets), otherwise write to the local filesystem
61
+ const streamToUse = args?.stream || fs.createWriteStream(fullPathName);
62
+ await pipeline(response.data, streamToUse);
34
63
  const contentType = response?.headers?.[HEADERS.CONTENT_TYPE] || '';
35
64
  const [mimeType, charset] = contentType.split('; ');
36
65
  const encoding = charset?.startsWith(CHARSET) ? charset.slice(CHARSET.length) : '';
@@ -44,23 +73,24 @@ export const downloadFile = async (args) => {
44
73
  });
45
74
  }
46
75
  catch (ex) {
47
- return OpResult.fail(OP_RESULT_CODES.FAILED, { url: url.toString(), fileName, fullPathName, size: 0, mimeType: '' }, ex.message);
76
+ // Include HTTP status code in the message when available (axios throws
77
+ // for 4xx/5xx responses with ex.response.status populated)
78
+ const statusCode = ex?.response?.status;
79
+ const message = statusCode ? `HTTP ${statusCode}: ${ex.message}` : ex.message;
80
+ return OpResult.fail(OP_RESULT_CODES.FAILED, { url: url.toString(), fileName, fullPathName, size: 0, mimeType: '' }, message);
48
81
  }
49
82
  });
50
- const data = result.getDataFirst();
51
- result.setData({ ...data, speed: (data.size * 1000) / durationMs, durationMs });
83
+ // Only enrich the result with speed/duration when the download succeeded —
84
+ // a failed result has no size to calculate speed from, and spreading null
85
+ // data would throw TypeError
86
+ if (result.didSucceed()) {
87
+ const data = result.getDataFirst() ?? {};
88
+ result.setData({
89
+ ...data,
90
+ // Guard against zero duration (e.g. cached response or measurement anomaly)
91
+ speed: durationMs > 0 ? (data.size * 1000) / durationMs : 0,
92
+ durationMs,
93
+ });
94
+ }
52
95
  return result;
53
96
  };
54
- // const run = async () => {
55
- // // const result = await downloadFile({
56
- // // url: 'https://sushitei.com/wp-content/uploads/2022/08/2022-Sushi-Tei-Autumn-Menu.pdf',
57
- // // fileName: '',
58
- // // });
59
- // const result = await downloadFile({
60
- // url: 'https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v6.15/windows/pgadmin4-6.15-x64.exe',
61
- // fileName: '',
62
- // folder: path.resolve('d:\\Users\\dcerge\\Downloads'),
63
- // });
64
- // console.log('result', JSON.stringify(result, null, 2));
65
- // };
66
- // run();
@@ -1,6 +1,6 @@
1
1
  export * from './constants';
2
2
  export * from './interfaces';
3
- export * from './configBulder';
3
+ export * from './configBuilder';
4
4
  export * from './Database';
5
5
  export * from './dbHelpers';
6
6
  export * from './DbMigratorAndSeeder';
@@ -12,10 +12,14 @@ export * from './DataCache';
12
12
  export * from './BaseGateway';
13
13
  export * from './BaseCore';
14
14
  export * from './apiContext';
15
- export * from './baseController';
15
+ export * from './BaseController';
16
16
  export * from './dbTableHelpers';
17
17
  export * from './resolversHelpers';
18
18
  export * from './userToken';
19
19
  export * from './passwordHelpers';
20
20
  export * from './commonValidators';
21
21
  export * from './downloadHelpers';
22
+ export * from './resolveClientIp';
23
+ export * from './BaseRestApiCrudController';
24
+ export * from './BaseExternalApiGateway';
25
+ export * from './IpRateLimiter';
@@ -1,6 +1,6 @@
1
1
  export * from './constants';
2
2
  export * from './interfaces';
3
- export * from './configBulder';
3
+ export * from './configBuilder';
4
4
  export * from './Database';
5
5
  export * from './dbHelpers';
6
6
  export * from './DbMigratorAndSeeder';
@@ -12,10 +12,14 @@ export * from './DataCache';
12
12
  export * from './BaseGateway';
13
13
  export * from './BaseCore';
14
14
  export * from './apiContext';
15
- export * from './baseController';
15
+ export * from './BaseController';
16
16
  export * from './dbTableHelpers';
17
17
  export * from './resolversHelpers';
18
18
  export * from './userToken';
19
19
  export * from './passwordHelpers';
20
20
  export * from './commonValidators';
21
21
  export * from './downloadHelpers';
22
+ export * from './resolveClientIp';
23
+ export * from './BaseRestApiCrudController';
24
+ export * from './BaseExternalApiGateway';
25
+ export * from './IpRateLimiter';
@@ -1,12 +1,16 @@
1
- /**
2
- * Interface of application API interface which should be created on receiving of a request
3
- */
1
+ import { RateLimiterInterface, RateLimitRule } from '../IpRateLimiter';
4
2
  export interface ApiContext {
5
3
  requestId: string;
6
4
  cores: any;
7
5
  gateways: any;
6
+ usedKeyPrefixes: Record<string, any>;
8
7
  req: any;
9
8
  res?: any;
9
+ db?: any;
10
+ headers?: Record<string, any>;
11
+ cookies?: Record<string, any>;
12
+ isExternalDb?: boolean;
13
+ authorizationToken?: string;
10
14
  spaceId?: string;
11
15
  apiKey?: string;
12
16
  managementApiKey?: string;
@@ -17,9 +21,35 @@ export interface ApiContext {
17
21
  languages?: string[];
18
22
  requestedLang?: string;
19
23
  authorization?: string;
24
+ fingerprint?: string;
20
25
  accountId?: string;
21
26
  roleId?: string;
22
27
  userId?: string;
23
28
  lang?: string;
29
+ /**
30
+ * App-level rate-limiter singleton. Created once at startup (e.g. in
31
+ * createContextDefault) and shared across every core in every request.
32
+ *
33
+ * BaseCore.getRateLimiter() reads this field when no per-core override is
34
+ * set in BaseCorePropsInterface.rateLimiter. Setting it to null on the
35
+ * context disables rate limiting for all cores that don't have their own
36
+ * override.
37
+ *
38
+ * Typed as RateLimiterInterface so any compatible implementation works —
39
+ * the built-in IpRateLimiter is the default but tests can swap in a no-op.
40
+ */
41
+ rateLimiter?: RateLimiterInterface | null;
42
+ /**
43
+ * Service-wide rate-limit rule applied as a global tier on every runAction
44
+ * call across all cores. Runs independently alongside the core-or-action
45
+ * tier — both must pass. Cannot be opted out by per-core or per-action config.
46
+ *
47
+ * Set once at app startup via createContextDefault (or your own context
48
+ * factory). Leave unset to skip the global tier entirely.
49
+ *
50
+ * Example — cap every IP at 300 requests per minute across the whole service:
51
+ * globalRateLimit: { limit: 300, windowSec: 60 }
52
+ */
53
+ globalRateLimit?: RateLimitRule;
24
54
  [key: string]: any;
25
55
  }
@@ -1 +1,2 @@
1
+ // ./src/interfaces/ApiContext.ts
1
2
  export {};
@@ -5,7 +5,7 @@ export interface ApiContextInterface {
5
5
  gateways: any;
6
6
  req: any;
7
7
  res: any;
8
- requestId: any;
8
+ requestId?: string;
9
9
  getCoreContext?(args: any): Promise<BaseCorePropsInterface>;
10
10
  getGatewayContext?(args: any): Promise<BaseGatewayPropsInterface>;
11
11
  extendContext?(args: any): any;
@@ -0,0 +1,5 @@
1
+ import { Logger } from '@sdflc/utils';
2
+ export interface BaseControllerPropsInterface {
3
+ onResponse?: (req: any, res: any, next: any) => Promise<void> | void;
4
+ logger?: Logger;
5
+ }
@@ -9,4 +9,5 @@ export interface BaseCoreDoAuthOnActionInterface {
9
9
  set?: boolean;
10
10
  remove?: boolean;
11
11
  removeMany?: boolean;
12
+ [key: string]: boolean | undefined;
12
13
  }
@@ -1,13 +1,13 @@
1
1
  export interface BaseCoreDoingWhatInterface {
2
- list: string;
3
- get: string;
4
- getMany: string;
5
- create: string;
6
- createMany: string;
7
- update: string;
8
- updateMany: string;
9
- set: string;
10
- remove: string;
11
- removeMany: string;
12
- [key: string]: string;
2
+ list?: string;
3
+ get?: string;
4
+ getMany?: string;
5
+ create?: string;
6
+ createMany?: string;
7
+ update?: string;
8
+ updateMany?: string;
9
+ set?: string;
10
+ remove?: string;
11
+ removeMany?: string;
12
+ [key: string]: string | undefined;
13
13
  }