@sdflc/backend-helpers 1.0.111 → 1.0.113

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 (206) 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 +470 -33
  5. package/build/BaseCore.js +613 -126
  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/RedisDataLoader.d.ts +144 -21
  19. package/build/RedisDataLoader.js +178 -49
  20. package/build/apiContext.d.ts +0 -8
  21. package/build/apiContext.js +12 -27
  22. package/build/checkItHelpers.d.ts +32 -0
  23. package/build/checkItHelpers.js +73 -7
  24. package/build/commonValidators.d.ts +107 -16
  25. package/build/commonValidators.js +211 -106
  26. package/build/configBuilder.d.ts +23 -0
  27. package/build/configBuilder.js +73 -0
  28. package/build/constants.d.ts +134 -17
  29. package/build/constants.js +95 -15
  30. package/build/dbHelpers.d.ts +89 -29
  31. package/build/dbHelpers.js +175 -86
  32. package/build/dbSeeder.d.ts +10 -1
  33. package/build/dbSeeder.js +80 -15
  34. package/build/dbTableHelpers.d.ts +122 -5
  35. package/build/dbTableHelpers.js +151 -13
  36. package/build/downloadHelpers.d.ts +24 -1
  37. package/build/downloadHelpers.js +51 -21
  38. package/build/esm/BaseController.d.ts +20 -0
  39. package/build/esm/BaseController.js +58 -0
  40. package/build/esm/BaseCore.d.ts +470 -33
  41. package/build/esm/BaseCore.js +615 -128
  42. package/build/esm/BaseExternalApiGateway.d.ts +16 -0
  43. package/build/esm/BaseExternalApiGateway.js +48 -0
  44. package/build/esm/BaseGateway.d.ts +455 -17
  45. package/build/esm/BaseGateway.js +503 -57
  46. package/build/esm/BaseRestApiCrudController.d.ts +37 -0
  47. package/build/esm/BaseRestApiCrudController.js +131 -0
  48. package/build/esm/DataCache.d.ts +116 -5
  49. package/build/esm/DataCache.js +142 -20
  50. package/build/esm/Database.d.ts +165 -4
  51. package/build/esm/Database.js +224 -51
  52. package/build/esm/DbMigratorAndSeeder.d.ts +127 -26
  53. package/build/esm/DbMigratorAndSeeder.js +184 -71
  54. package/build/esm/RedisDataLoader.d.ts +144 -21
  55. package/build/esm/RedisDataLoader.js +179 -50
  56. package/build/esm/apiContext.d.ts +0 -8
  57. package/build/esm/apiContext.js +12 -27
  58. package/build/esm/checkItHelpers.d.ts +32 -0
  59. package/build/esm/checkItHelpers.js +73 -7
  60. package/build/esm/commonValidators.d.ts +107 -16
  61. package/build/esm/commonValidators.js +209 -105
  62. package/build/esm/configBuilder.d.ts +23 -0
  63. package/build/esm/configBuilder.js +69 -0
  64. package/build/esm/constants.d.ts +134 -17
  65. package/build/esm/constants.js +94 -14
  66. package/build/esm/dbHelpers.d.ts +89 -29
  67. package/build/esm/dbHelpers.js +171 -81
  68. package/build/esm/dbSeeder.d.ts +10 -1
  69. package/build/esm/dbSeeder.js +81 -16
  70. package/build/esm/dbTableHelpers.d.ts +122 -5
  71. package/build/esm/dbTableHelpers.js +152 -14
  72. package/build/esm/downloadHelpers.d.ts +24 -1
  73. package/build/esm/downloadHelpers.js +51 -21
  74. package/build/esm/index.d.ts +5 -2
  75. package/build/esm/index.js +5 -2
  76. package/build/esm/interfaces/ApiContext.d.ts +7 -3
  77. package/build/esm/interfaces/ApiContextInterface.d.ts +1 -1
  78. package/build/esm/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  79. package/build/esm/interfaces/BaseControllerPropsInterface.js +1 -0
  80. package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  81. package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  82. package/build/esm/interfaces/BaseCorePropsInterface.d.ts +87 -9
  83. package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
  84. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  85. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.js +2 -0
  86. package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  87. package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
  88. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  89. package/build/esm/interfaces/BaseRestApiCrudControllerPropsInterface.js +2 -0
  90. package/build/esm/interfaces/BuildConfigOptions.d.ts +18 -0
  91. package/build/esm/interfaces/BuildConfigOptions.js +1 -0
  92. package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  93. package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
  94. package/build/esm/interfaces/CacheInterface.d.ts +18 -1
  95. package/build/esm/interfaces/CacheInterface.js +1 -0
  96. package/build/esm/interfaces/CoreActionInterface.d.ts +20 -0
  97. package/build/esm/interfaces/CreateUserTokenArgs.d.ts +38 -4
  98. package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
  99. package/build/esm/interfaces/DataCachePropsInterface.d.ts +21 -0
  100. package/build/esm/interfaces/DataCachePropsInterface.js +2 -0
  101. package/build/esm/interfaces/DatabaseOptions.d.ts +24 -10
  102. package/build/esm/interfaces/DatabaseOptions.js +1 -0
  103. package/build/esm/interfaces/DatabaseReadInterface.d.ts +58 -3
  104. package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
  105. package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  106. package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
  107. package/build/esm/interfaces/DownloadFileArgs.d.ts +21 -2
  108. package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  109. package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
  110. package/build/esm/interfaces/ListArgsInterface.d.ts +18 -0
  111. package/build/esm/interfaces/ListArgsInterface.js +1 -0
  112. package/build/esm/interfaces/LoaderInterface.d.ts +36 -1
  113. package/build/esm/interfaces/LoaderInterface.js +1 -0
  114. package/build/esm/interfaces/UserTokenParams.d.ts +23 -5
  115. package/build/esm/interfaces/UserTokenParams.js +1 -0
  116. package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  117. package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
  118. package/build/esm/interfaces/index.d.ts +4 -0
  119. package/build/esm/interfaces/index.js +4 -0
  120. package/build/esm/knexConfigBuilder.d.ts +25 -0
  121. package/build/esm/knexConfigBuilder.js +100 -36
  122. package/build/esm/parseIds.d.ts +6 -0
  123. package/build/esm/parseIds.js +13 -0
  124. package/build/esm/passwordHelpers.d.ts +22 -0
  125. package/build/esm/passwordHelpers.js +40 -8
  126. package/build/esm/redisClient.d.ts +57 -4
  127. package/build/esm/redisClient.js +40 -54
  128. package/build/esm/resolveClientIp.d.ts +15 -0
  129. package/build/esm/resolveClientIp.js +34 -0
  130. package/build/esm/resolversHelpers.d.ts +21 -1
  131. package/build/esm/resolversHelpers.js +48 -26
  132. package/build/esm/userToken.d.ts +50 -1
  133. package/build/esm/userToken.js +85 -20
  134. package/build/esm/utils.d.ts +20 -0
  135. package/build/esm/utils.js +23 -1
  136. package/build/index.d.ts +5 -2
  137. package/build/index.js +5 -2
  138. package/build/interfaces/ApiContext.d.ts +7 -3
  139. package/build/interfaces/ApiContextInterface.d.ts +1 -1
  140. package/build/interfaces/BaseControllerPropsInterface.d.ts +5 -0
  141. package/build/interfaces/BaseControllerPropsInterface.js +2 -0
  142. package/build/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +1 -0
  143. package/build/interfaces/BaseCoreDoingWhatInterface.d.ts +11 -11
  144. package/build/interfaces/BaseCorePropsInterface.d.ts +87 -9
  145. package/build/interfaces/BaseCorePropsInterface.js +1 -0
  146. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +19 -0
  147. package/build/interfaces/BaseExternalApiGatewayPropsInterface.js +3 -0
  148. package/build/interfaces/BaseGatewayPropsInterface.d.ts +78 -3
  149. package/build/interfaces/BaseGatewayPropsInterface.js +1 -0
  150. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.d.ts +28 -0
  151. package/build/interfaces/BaseRestApiCrudControllerPropsInterface.js +3 -0
  152. package/build/interfaces/BuildConfigOptions.d.ts +18 -0
  153. package/build/interfaces/BuildConfigOptions.js +1 -0
  154. package/build/interfaces/BuildListQueryArgsInterface.d.ts +22 -4
  155. package/build/interfaces/BuildListQueryArgsInterface.js +1 -0
  156. package/build/interfaces/CacheInterface.d.ts +18 -1
  157. package/build/interfaces/CacheInterface.js +1 -0
  158. package/build/interfaces/CoreActionInterface.d.ts +20 -0
  159. package/build/interfaces/CreateUserTokenArgs.d.ts +38 -4
  160. package/build/interfaces/CreateUserTokenArgs.js +1 -0
  161. package/build/interfaces/DataCachePropsInterface.d.ts +21 -0
  162. package/build/interfaces/DataCachePropsInterface.js +3 -0
  163. package/build/interfaces/DatabaseOptions.d.ts +24 -10
  164. package/build/interfaces/DatabaseOptions.js +1 -0
  165. package/build/interfaces/DatabaseReadInterface.d.ts +58 -3
  166. package/build/interfaces/DatabaseReadInterface.js +1 -0
  167. package/build/interfaces/DbFieldAddDefaultInterface.d.ts +35 -4
  168. package/build/interfaces/DbFieldAddDefaultInterface.js +1 -0
  169. package/build/interfaces/DownloadFileArgs.d.ts +21 -2
  170. package/build/interfaces/ExtractCredentialsArgs.d.ts +15 -4
  171. package/build/interfaces/ExtractCredentialsArgs.js +1 -0
  172. package/build/interfaces/ListArgsInterface.d.ts +18 -0
  173. package/build/interfaces/ListArgsInterface.js +1 -0
  174. package/build/interfaces/LoaderInterface.d.ts +36 -1
  175. package/build/interfaces/LoaderInterface.js +1 -0
  176. package/build/interfaces/UserTokenParams.d.ts +23 -5
  177. package/build/interfaces/UserTokenParams.js +1 -0
  178. package/build/interfaces/VerifyUserTokenArgs.d.ts +42 -2
  179. package/build/interfaces/VerifyUserTokenArgs.js +1 -0
  180. package/build/interfaces/index.d.ts +4 -0
  181. package/build/interfaces/index.js +4 -0
  182. package/build/knexConfigBuilder.d.ts +25 -0
  183. package/build/knexConfigBuilder.js +99 -35
  184. package/build/parseIds.d.ts +6 -0
  185. package/build/parseIds.js +17 -0
  186. package/build/passwordHelpers.d.ts +22 -0
  187. package/build/passwordHelpers.js +40 -8
  188. package/build/redisClient.d.ts +57 -4
  189. package/build/redisClient.js +40 -54
  190. package/build/resolveClientIp.d.ts +15 -0
  191. package/build/resolveClientIp.js +38 -0
  192. package/build/resolversHelpers.d.ts +21 -1
  193. package/build/resolversHelpers.js +48 -26
  194. package/build/userToken.d.ts +50 -1
  195. package/build/userToken.js +85 -20
  196. package/build/utils.d.ts +20 -0
  197. package/build/utils.js +23 -1
  198. package/package.json +19 -18
  199. package/build/baseController.d.ts +0 -17
  200. package/build/baseController.js +0 -63
  201. package/build/configBulder.d.ts +0 -2
  202. package/build/configBulder.js +0 -36
  203. package/build/esm/baseController.d.ts +0 -17
  204. package/build/esm/baseController.js +0 -57
  205. package/build/esm/configBulder.d.ts +0 -2
  206. 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,13 @@ 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';
@@ -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,13 @@ 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';
@@ -1,12 +1,15 @@
1
- /**
2
- * Interface of application API interface which should be created on receiving of a request
3
- */
4
1
  export interface ApiContext {
5
2
  requestId: string;
6
3
  cores: any;
7
4
  gateways: any;
5
+ usedKeyPrefixes: Record<string, any>;
8
6
  req: any;
9
7
  res?: any;
8
+ db?: any;
9
+ headers?: Record<string, any>;
10
+ cookies?: Record<string, any>;
11
+ isExternalDb?: boolean;
12
+ authorizationToken?: string;
10
13
  spaceId?: string;
11
14
  apiKey?: string;
12
15
  managementApiKey?: string;
@@ -17,6 +20,7 @@ export interface ApiContext {
17
20
  languages?: string[];
18
21
  requestedLang?: string;
19
22
  authorization?: string;
23
+ fingerprint?: string;
20
24
  accountId?: string;
21
25
  roleId?: string;
22
26
  userId?: string;
@@ -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
  }
@@ -1,6 +1,5 @@
1
1
  import { Logger } from '@sdflc/utils';
2
2
  import { Database } from '../Database';
3
- import { BaseGateway } from '../BaseGateway';
4
3
  import { BaseCoreValidatorsInterface } from './BaseCoreValidatorsInterface';
5
4
  import { BaseCoreDoingWhatInterface } from './BaseCoreDoingWhatInterface';
6
5
  import { VerifyUserTokenArgs } from './VerifyUserTokenArgs';
@@ -9,29 +8,108 @@ import { ID_TYPES } from '../constants';
9
8
  import { BaseCoreDoAuthOnActionInterface } from './BaseCoreDoAuthOnActionInterface';
10
9
  export interface BaseCorePropsInterface {
11
10
  /**
12
- * Application API context with all necessary information about request
11
+ * Full request-scoped ApiContext. Required — cores use it to access
12
+ * userId, spaceId, gateways, requestId, headers, etc.
13
13
  */
14
14
  context: ApiContext;
15
15
  /**
16
- * Database instance to handle queries to DB within one request
16
+ * Database instance for transaction management and raw query access.
17
+ * Required — used by runAction() for startTransaction, commit, rollback,
18
+ * and by exceptionFailure() for isDbError() checks.
17
19
  */
18
20
  db: Database;
19
21
  /**
20
- * Name of a gateway that will perform default CRUD operations, it should be initialized in the API context
22
+ * Name of the default gateway in context.gateways used for CRUD operations.
23
+ * Optional — some cores orchestrate other cores or always specify the
24
+ * gateway name explicitly via getGateway(name).
25
+ */
26
+ gatewayName?: string;
27
+ /**
28
+ * Optional — available to subclasses that vary behaviour between
29
+ * production and non-production environments (e.g. verbose error messages).
30
+ */
31
+ isProduction?: boolean;
32
+ /**
33
+ * Optional — falls back to a module-level Logger({ level: ERROR }) if not
34
+ * provided or if the value fails the isLogger() duck-type check.
35
+ * Duck-typed to avoid instanceof failures across package versions.
36
+ */
37
+ logger?: Logger;
38
+ /**
39
+ * Human-readable name for this core. Used as the default `doingWhat`
40
+ * string in log messages and error reports when doingWhat is not set.
21
41
  */
22
- gatewayName: string;
23
- isProduction: boolean;
24
- logger: Logger;
25
42
  name?: string;
26
- doAuth: boolean;
43
+ /**
44
+ * Master auth switch. When true, all actions require authentication
45
+ * unless overridden per-action via doAuthOnAction.
46
+ * Optional — defaults to false (no auth required).
47
+ */
48
+ doAuth?: boolean;
49
+ /**
50
+ * Per-action auth overrides. Each action independently enables or disables
51
+ * auth. Falls back to doAuth if not set for a specific action.
52
+ *
53
+ * Example — require auth globally but allow public list:
54
+ * { doAuth: true, doAuthOnAction: { list: false } }
55
+ */
27
56
  doAuthOnAction?: BaseCoreDoAuthOnActionInterface;
57
+ /**
58
+ * Custom doingWhat strings for log messages per action.
59
+ * e.g. { create: 'creating a user account', remove: 'deleting a user' }
60
+ * Falls back to `name` then to a built-in default string if not set.
61
+ */
28
62
  doingWhat?: BaseCoreDoingWhatInterface;
63
+ /**
64
+ * Custom validator map. If not provided, getValidators() returns the
65
+ * default validators (validateGet, validateGetMany, validateRemove,
66
+ * validateRemoveMany, and no-op defaults for mutations).
67
+ */
29
68
  validators?: BaseCoreValidatorsInterface;
30
- spaceGw?: BaseGateway;
69
+ /**
70
+ * Gateway used to resolve the current space by spaceId.
71
+ * Typed structurally rather than as BaseGateway to avoid instanceof
72
+ * coupling across package versions — any object with a get() method works.
73
+ *
74
+ * Used by findSpace() to look up space config (tokenSecret, apiKey, etc.)
75
+ * when context.space is not already populated.
76
+ */
77
+ spaceGw?: {
78
+ get(id: string): Promise<any>;
79
+ };
80
+ /**
81
+ * Shared secret for service-to-service API calls.
82
+ * When context.apiKey matches this value, authentication is bypassed
83
+ * and the request is treated as a trusted interservice call.
84
+ */
31
85
  interserviceApiKey?: string;
86
+ /**
87
+ * JWT secret used to verify user tokens.
88
+ * Can be overridden per-space via getJwtTokenSecretAndSettings().
89
+ */
32
90
  jwtSecret?: string;
91
+ /**
92
+ * Additional options passed to the JWT verification function.
93
+ * e.g. algorithms, audience, issuer, clockTolerance.
94
+ * Merged with defaults in getJwtTokenSecretAndSettings().
95
+ */
33
96
  verifyTokenArgs?: VerifyUserTokenArgs;
97
+ /**
98
+ * When true, create() automatically calculates and sets the orderNo
99
+ * field before inserting. Uses getFilterToSetOrderNo() to scope the
100
+ * sequence and getGatewayToSetOrerNo() to query the current max.
101
+ */
34
102
  hasOrderNo?: boolean;
103
+ /**
104
+ * Controls the orderNo strategy when hasOrderNo is true.
105
+ * true — numeric ordering (10, 20, 30...)
106
+ * false — lexicographic string ordering via StrOrderHelpers
107
+ */
35
108
  orderNoAsDecimal?: boolean;
109
+ /**
110
+ * The ID type this core operates with (UUID, integer, etc.).
111
+ * Used by consumers that need to validate or coerce ID formats.
112
+ * Defaults to ID_TYPES.UNKNOWN if not set.
113
+ */
36
114
  idType?: ID_TYPES;
37
115
  }
@@ -1 +1,2 @@
1
+ // ./src/interfaces/BaseCorePropsInterface.ts
1
2
  export {};
@@ -0,0 +1,19 @@
1
+ export interface BaseExternalApiGatewayPropsInterface {
2
+ /**
3
+ * Optional credentials — a plain API key string or a structured object
4
+ * with whatever keys the external service requires.
5
+ * Can also be set later via setCredentials() once resolved at runtime.
6
+ */
7
+ credentials?: string | Record<string, any>;
8
+ /**
9
+ * Base URL of the external API.
10
+ * Can be overridden in the subclass if it never changes.
11
+ */
12
+ baseUrl?: string;
13
+ /**
14
+ * Timeout in milliseconds for outbound requests.
15
+ * Defaults to 10000.
16
+ */
17
+ timeoutMs?: number;
18
+ logger?: any;
19
+ }
@@ -0,0 +1,2 @@
1
+ // ./src/interfaces/BaseExternalApiGatewayPropsInterface.ts
2
+ export {};