@sdflc/backend-helpers 1.0.112 → 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 +608 -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/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 +599 -118
  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 -2
  135. package/build/esm/utils.js +23 -13
  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 -2
  197. package/build/utils.js +24 -16
  198. package/package.json +19 -18
  199. package/build/baseController.d.ts +0 -17
  200. package/build/baseController.js +0 -64
  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 -58
  205. package/build/esm/configBulder.d.ts +0 -2
  206. package/build/esm/configBulder.js +0 -32
@@ -1,4 +1,20 @@
1
1
  import { DatabaseOptions, DatabaseReadInterface } from './interfaces';
2
+ /**
3
+ * Database is a thin wrapper around a Knex connection that adds:
4
+ * - Connection pool deduplication (one Knex instance per unique connection config)
5
+ * - Transaction lifecycle management (start, commit, rollback)
6
+ * - Schema-scoped query builder
7
+ * - Common DB error classification (isDbError)
8
+ * - Utility methods for pagination, sorting, calculated fields, and raw reads
9
+ *
10
+ * One Database instance is created per request in createContextDefault() and
11
+ * shared across all gateways via ApiContext. This ensures all gateways in a
12
+ * single request share the same transaction when one is active.
13
+ *
14
+ * Connection pools are shared across requests via the module-level knexHandles
15
+ * cache — creating a new Database instance does not open a new connection pool
16
+ * if one already exists for the same host/port/user/database/schema combination.
17
+ */
2
18
  declare class Database {
3
19
  private trx;
4
20
  private dbType;
@@ -6,31 +22,176 @@ declare class Database {
6
22
  private dbSchema;
7
23
  private logger;
8
24
  constructor(props: DatabaseOptions);
25
+ /**
26
+ * Destroys the Knex connection pool for this instance.
27
+ * Call on application shutdown to cleanly close all DB connections.
28
+ * Note: affects all instances sharing this pool — use with care.
29
+ */
9
30
  destroy(): void;
10
- isDbError(ex: any): any[];
11
- createTransaction(trx: any): Promise<unknown>;
31
+ /**
32
+ * Classifies a caught database error by its PostgreSQL error code.
33
+ * Returns `[true, humanMessage]` for known DB errors that are safe to
34
+ * surface to the client, or `[false, '']` for unknown errors.
35
+ *
36
+ * Known codes:
37
+ * 23503 — foreign key violation (referenced record does not exist)
38
+ * 23505 — unique constraint violation (record already exists)
39
+ *
40
+ * Used by BaseCore.exceptionFailure() to decide whether to return the
41
+ * DB error message directly or log it and return a generic message.
42
+ */
43
+ isDbError(ex: any): [boolean, string];
44
+ /**
45
+ * Creates a new Knex transaction.
46
+ * If `trx` is provided, creates a nested transaction on the existing one.
47
+ * Prefer `startTransaction()` for standard usage — this method is lower-level.
48
+ */
49
+ createTransaction(trx: any): Promise<any>;
50
+ /**
51
+ * Returns the database type string (e.g. 'pg', 'mysql2', 'sqlite3').
52
+ * Used by gateways to build type-specific query fragments.
53
+ */
12
54
  getDbType(): string;
55
+ /**
56
+ * Returns the configured schema name, or empty string if not set.
57
+ */
13
58
  getSchema(): string;
59
+ /**
60
+ * Returns a Knex query builder for the given table, scoped to the
61
+ * configured schema if one is set. Uses the active transaction if present.
62
+ *
63
+ * Fix: withSchema() is only called when dbSchema is non-empty — passing
64
+ * an empty string to withSchema() causes unexpected behaviour in some drivers.
65
+ *
66
+ * @param arg Table name or Knex raw expression
67
+ */
14
68
  getBuilder(arg: any): any;
69
+ /**
70
+ * Returns a Knex raw expression. Useful for CONCAT, uuid_generate_v4(),
71
+ * and other DB-level expressions used in gateway transforms.
72
+ *
73
+ * @param query Raw SQL string with optional `?` placeholders
74
+ * @param bindings Values to bind to `?` placeholders
75
+ */
15
76
  raw(query: string, bindings?: any): any;
77
+ /**
78
+ * Executes a raw SQL query against the database.
79
+ * Uses the active transaction if present.
80
+ *
81
+ * @param query Raw SQL string with optional `?` placeholders
82
+ * @param bindings Values to bind to `?` placeholders
83
+ */
16
84
  runRawQuery(query: string, bindings: any): Promise<any>;
17
- startTransaction(): Promise<unknown>;
85
+ /**
86
+ * Starts a new database transaction and stores it on this instance.
87
+ * All subsequent `getBuilder()` calls will use the transaction until
88
+ * `commitTransaction()` or `rollbackTransaction()` is called.
89
+ *
90
+ * Guard: if a transaction is already active, logs a warning and returns
91
+ * the existing transaction rather than creating a nested one. Most databases
92
+ * do not support true nested transactions — the sameRequest flag in
93
+ * BaseCore.runAction() is the primary guard, but this adds a safety net.
94
+ *
95
+ * @returns The Knex transaction object
96
+ */
97
+ startTransaction(): Promise<any>;
98
+ /**
99
+ * Replaces the active transaction with the provided one.
100
+ * Use when a transaction was created externally (e.g. passed in from a
101
+ * test harness or a parent transaction manager).
102
+ */
18
103
  setTransaction(trx: any): void;
104
+ /**
105
+ * Returns the active transaction, or null if none is active.
106
+ */
19
107
  getTransaction(): any;
108
+ /**
109
+ * Commits the active transaction and clears it from this instance.
110
+ * Does nothing if no transaction is active.
111
+ */
20
112
  commitTransaction(): Promise<void>;
113
+ /**
114
+ * Rolls back the active transaction and clears it from this instance.
115
+ * Does nothing if no transaction is active.
116
+ *
117
+ * Rollback errors are caught and logged rather than re-thrown — a failed
118
+ * rollback is logged for observability but should not mask the original
119
+ * exception that triggered the rollback.
120
+ */
21
121
  rollbackTransaction(): Promise<void>;
122
+ /**
123
+ * Applies calculated field values to a single result row.
124
+ * Each entry in `calculatedFields` specifies a field name and either a
125
+ * static value or a function that receives the row and returns a value.
126
+ *
127
+ * Entries with no `name` are silently skipped with a warning.
128
+ *
129
+ * @param item The result row to mutate
130
+ * @param calculatedFields Array of { name, value } descriptors
131
+ */
22
132
  doCalculated(item: any, calculatedFields: any[]): void;
23
- read(args: DatabaseReadInterface): Promise<any>;
133
+ /**
134
+ * Executes a SELECT query with optional WHERE, whereIn, and query extension,
135
+ * then optionally maps results into a keyed object and/or applies
136
+ * calculated fields to each row.
137
+ *
138
+ * When `mapBy` is set, returns a `Record<string, row>` keyed by the
139
+ * camelCase value of `mapBy` field on each row, processed through
140
+ * `buildKey` (defaults to the `buildKey` from @sdflc/utils).
141
+ * When `mapBy` is not set, returns a plain array.
142
+ *
143
+ * @param args DatabaseReadInterface describing the query
144
+ */
145
+ read(args: DatabaseReadInterface): Promise<any[] | Record<string, any>>;
146
+ /**
147
+ * Converts a sortBy array from the API params format into the Knex
148
+ * `orderBy` format `[{ column, order }]`.
149
+ *
150
+ * Falls back to `defaultSortBy` if `sortBy` is null/undefined.
151
+ * Returns null if neither is provided — callers should skip `orderBy()`
152
+ * when this returns null.
153
+ *
154
+ * @param sortBy Array of `{ name, order }` from request params
155
+ * @param defaultSortBy Fallback sort config from gateway config
156
+ */
24
157
  createSortBy(sortBy: any[], defaultSortBy?: any): any[] | null;
158
+ /**
159
+ * Calculates `limit` and `offset` values from page/pageSize pagination params.
160
+ *
161
+ * Page is 1-indexed — page 1 with pageSize 10 gives offset 0.
162
+ * If `pageSize` is absent or NaN, `limit` is undefined (no limit applied).
163
+ * If `page` is absent, NaN, or < 1, it defaults to 1.
164
+ *
165
+ * @param page 1-based page number
166
+ * @param pageSize Number of records per page
167
+ */
25
168
  createLimitOffset(page: number, pageSize: number): {
26
169
  limit: number | undefined;
27
170
  offset: number;
28
171
  };
172
+ /**
173
+ * Combines `createLimitOffset()` and `createSortBy()` into a single call,
174
+ * reading pagination and sorting from the standard request params shape:
175
+ * `{ pagination: { page, pageSize }, sortBy: [{ name, order }] }`.
176
+ *
177
+ * Returns `{ limit, offset, sortBy }` ready to be applied to a Knex query.
178
+ * `sortBy` may be null if no sort is configured — callers should skip
179
+ * `query.orderBy()` in that case.
180
+ *
181
+ * @param params Request params object (may be null/undefined)
182
+ * @param defaultSortBy Fallback sort config from gateway config
183
+ */
29
184
  createLimitOffsetSortBy(params: any, defaultSortBy: any): {
30
185
  limit: number | undefined;
31
186
  offset: number;
32
187
  sortBy: any[] | null;
33
188
  };
189
+ /**
190
+ * Destroys the shared Knex connection pool for the given config.
191
+ * Use on application shutdown or in tests that need to reset the pool.
192
+ *
193
+ * Static because the pool is module-level — no instance needed.
194
+ */
34
195
  static destroyHandle(props: DatabaseOptions): void;
35
196
  }
36
197
  export { Database };
package/build/Database.js CHANGED
@@ -1,19 +1,48 @@
1
1
  "use strict";
2
+ // ./src/Database.ts (capitalised to match class name convention)
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
7
  exports.Database = void 0;
7
- const lodash_1 = require("lodash");
8
+ const camelCase_1 = __importDefault(require("lodash/camelCase"));
8
9
  const knex_1 = __importDefault(require("knex"));
9
10
  const utils_1 = require("@sdflc/utils");
11
+ /**
12
+ * Module-level Knex handle cache keyed by connection config.
13
+ * Shared across all Database instances in the same process to avoid
14
+ * creating redundant connection pools for the same database.
15
+ *
16
+ * Key format: "host|port|user|database|schema"
17
+ * Note: password is intentionally excluded from the key to avoid
18
+ * storing credentials in memory beyond what the Knex driver requires.
19
+ */
10
20
  const knexHandles = {};
11
- const buildKey = (args) => {
21
+ /**
22
+ * Builds a deduplication key for the Knex handle cache from connection config.
23
+ * Excludes password to avoid unnecessary credential retention in memory.
24
+ */
25
+ const buildKnexCacheKey = (args) => {
12
26
  const { connection, dbSchema } = args || {};
13
- const { host, port, user, password, database } = connection || {};
14
- const parts = [host, port, user, password, database, dbSchema];
15
- return parts.join('|');
27
+ const { host, port, user, database } = connection || {};
28
+ return [host, port, user, database, dbSchema].join('|');
16
29
  };
30
+ /**
31
+ * Database is a thin wrapper around a Knex connection that adds:
32
+ * - Connection pool deduplication (one Knex instance per unique connection config)
33
+ * - Transaction lifecycle management (start, commit, rollback)
34
+ * - Schema-scoped query builder
35
+ * - Common DB error classification (isDbError)
36
+ * - Utility methods for pagination, sorting, calculated fields, and raw reads
37
+ *
38
+ * One Database instance is created per request in createContextDefault() and
39
+ * shared across all gateways via ApiContext. This ensures all gateways in a
40
+ * single request share the same transaction when one is active.
41
+ *
42
+ * Connection pools are shared across requests via the module-level knexHandles
43
+ * cache — creating a new Database instance does not open a new connection pool
44
+ * if one already exists for the same host/port/user/database/schema combination.
45
+ */
17
46
  class Database {
18
47
  trx = null;
19
48
  dbType = '';
@@ -24,10 +53,14 @@ class Database {
24
53
  if (!props.knexConfig) {
25
54
  throw new Error('The Database class expects to have `knexConfig` in its constructor props');
26
55
  }
27
- if (props.logger instanceof utils_1.Logger) {
56
+ // Duck-type check to avoid instanceof failures across package versions
57
+ if (props.logger && (0, utils_1.isLogger)(props.logger)) {
28
58
  this.logger = props.logger;
29
59
  }
30
- const cfgKey = buildKey({ connection: props.knexConfig.connection, dbSchema: props.dbSchema });
60
+ const cfgKey = buildKnexCacheKey({
61
+ connection: props.knexConfig.connection,
62
+ dbSchema: props.dbSchema,
63
+ });
31
64
  if (!knexHandles[cfgKey]) {
32
65
  this.logger.debug(`Create a new KnexJs configuration`);
33
66
  knexHandles[cfgKey] = (0, knex_1.default)(props.knexConfig);
@@ -38,85 +71,193 @@ class Database {
38
71
  this.knexHandle = knexHandles[cfgKey];
39
72
  this.dbType = props.dbType || props.knexConfig?.client || '';
40
73
  this.dbSchema = props.dbSchema || '';
41
- this.trx = props.trx;
74
+ this.trx = props.trx || null;
42
75
  }
76
+ /**
77
+ * Destroys the Knex connection pool for this instance.
78
+ * Call on application shutdown to cleanly close all DB connections.
79
+ * Note: affects all instances sharing this pool — use with care.
80
+ */
43
81
  destroy() {
44
82
  if (this.knexHandle) {
45
83
  this.knexHandle.destroy();
46
84
  }
47
85
  }
86
+ /**
87
+ * Classifies a caught database error by its PostgreSQL error code.
88
+ * Returns `[true, humanMessage]` for known DB errors that are safe to
89
+ * surface to the client, or `[false, '']` for unknown errors.
90
+ *
91
+ * Known codes:
92
+ * 23503 — foreign key violation (referenced record does not exist)
93
+ * 23505 — unique constraint violation (record already exists)
94
+ *
95
+ * Used by BaseCore.exceptionFailure() to decide whether to return the
96
+ * DB error message directly or log it and return a generic message.
97
+ */
48
98
  isDbError(ex) {
49
99
  const { code } = ex || {};
50
100
  switch (code) {
51
- default:
52
- return [false, ''];
53
101
  case '23503':
54
- // ex.detail: 'Key (message_id)=(78403d9e-4e95-4091-8136-ae99ddbfa3ca) is not present in table "message".',
55
- // ex.constraint: 'message_recipient_status_message_id_foreign',
56
- return [true, `Reference does not exist`];
102
+ return [true, 'Reference does not exist'];
57
103
  case '23505':
58
- return [true, `Such item already exists`];
104
+ return [true, 'Such item already exists'];
105
+ default:
106
+ return [false, ''];
59
107
  }
60
108
  }
61
- createTransaction(trx) {
62
- return new Promise((resolve) => {
63
- return (trx ? trx : this.knexHandle).transaction(resolve);
64
- });
109
+ /**
110
+ * Creates a new Knex transaction.
111
+ * If `trx` is provided, creates a nested transaction on the existing one.
112
+ * Prefer `startTransaction()` for standard usage — this method is lower-level.
113
+ */
114
+ async createTransaction(trx) {
115
+ return (trx ? trx : this.knexHandle).transaction();
65
116
  }
117
+ /**
118
+ * Returns the database type string (e.g. 'pg', 'mysql2', 'sqlite3').
119
+ * Used by gateways to build type-specific query fragments.
120
+ */
66
121
  getDbType() {
67
122
  return this.dbType;
68
123
  }
124
+ /**
125
+ * Returns the configured schema name, or empty string if not set.
126
+ */
69
127
  getSchema() {
70
128
  return this.dbSchema;
71
129
  }
130
+ /**
131
+ * Returns a Knex query builder for the given table, scoped to the
132
+ * configured schema if one is set. Uses the active transaction if present.
133
+ *
134
+ * Fix: withSchema() is only called when dbSchema is non-empty — passing
135
+ * an empty string to withSchema() causes unexpected behaviour in some drivers.
136
+ *
137
+ * @param arg Table name or Knex raw expression
138
+ */
72
139
  getBuilder(arg) {
73
- return this.trx ? this.trx(arg).withSchema(this.getSchema()) : this.knexHandle(arg).withSchema(this.getSchema());
140
+ const builder = this.trx ? this.trx(arg) : this.knexHandle(arg);
141
+ return this.dbSchema ? builder.withSchema(this.dbSchema) : builder;
74
142
  }
143
+ /**
144
+ * Returns a Knex raw expression. Useful for CONCAT, uuid_generate_v4(),
145
+ * and other DB-level expressions used in gateway transforms.
146
+ *
147
+ * @param query Raw SQL string with optional `?` placeholders
148
+ * @param bindings Values to bind to `?` placeholders
149
+ */
75
150
  raw(query, bindings) {
76
151
  return this.knexHandle.raw(query, bindings);
77
152
  }
153
+ /**
154
+ * Executes a raw SQL query against the database.
155
+ * Uses the active transaction if present.
156
+ *
157
+ * @param query Raw SQL string with optional `?` placeholders
158
+ * @param bindings Values to bind to `?` placeholders
159
+ */
78
160
  async runRawQuery(query, bindings) {
79
- const rows = await (this.trx ? this.trx : this.knexHandle).raw(query, bindings);
80
- return rows;
161
+ return (this.trx ? this.trx : this.knexHandle).raw(query, bindings);
81
162
  }
163
+ /**
164
+ * Starts a new database transaction and stores it on this instance.
165
+ * All subsequent `getBuilder()` calls will use the transaction until
166
+ * `commitTransaction()` or `rollbackTransaction()` is called.
167
+ *
168
+ * Guard: if a transaction is already active, logs a warning and returns
169
+ * the existing transaction rather than creating a nested one. Most databases
170
+ * do not support true nested transactions — the sameRequest flag in
171
+ * BaseCore.runAction() is the primary guard, but this adds a safety net.
172
+ *
173
+ * @returns The Knex transaction object
174
+ */
82
175
  async startTransaction() {
83
- const trx = await this.createTransaction(this.trx);
176
+ if (this.trx) {
177
+ this.logger.warn(`startTransaction called while a transaction is already active — reusing existing transaction`);
178
+ return this.trx;
179
+ }
180
+ const trx = await this.createTransaction(null);
84
181
  this.trx = trx;
85
182
  return trx;
86
183
  }
184
+ /**
185
+ * Replaces the active transaction with the provided one.
186
+ * Use when a transaction was created externally (e.g. passed in from a
187
+ * test harness or a parent transaction manager).
188
+ */
87
189
  setTransaction(trx) {
88
190
  this.trx = trx;
89
191
  }
192
+ /**
193
+ * Returns the active transaction, or null if none is active.
194
+ */
90
195
  getTransaction() {
91
196
  return this.trx;
92
197
  }
198
+ /**
199
+ * Commits the active transaction and clears it from this instance.
200
+ * Does nothing if no transaction is active.
201
+ */
93
202
  async commitTransaction() {
94
203
  if (this.trx) {
95
204
  await this.trx.commit();
96
- this.trx = undefined;
205
+ this.trx = null;
97
206
  }
98
207
  }
208
+ /**
209
+ * Rolls back the active transaction and clears it from this instance.
210
+ * Does nothing if no transaction is active.
211
+ *
212
+ * Rollback errors are caught and logged rather than re-thrown — a failed
213
+ * rollback is logged for observability but should not mask the original
214
+ * exception that triggered the rollback.
215
+ */
99
216
  async rollbackTransaction() {
100
217
  if (this.trx) {
101
218
  try {
102
219
  await this.trx.rollback();
103
220
  }
104
221
  catch (ex) {
105
- // Do nothing here
106
- this.logger.error(`Failed to rollback a transaction:`, ex.message);
222
+ this.logger.error(`Failed to rollback a transaction:`, ex?.message ?? String(ex));
107
223
  }
108
224
  }
109
- this.trx = undefined;
225
+ this.trx = null;
110
226
  }
227
+ /**
228
+ * Applies calculated field values to a single result row.
229
+ * Each entry in `calculatedFields` specifies a field name and either a
230
+ * static value or a function that receives the row and returns a value.
231
+ *
232
+ * Entries with no `name` are silently skipped with a warning.
233
+ *
234
+ * @param item The result row to mutate
235
+ * @param calculatedFields Array of { name, value } descriptors
236
+ */
111
237
  doCalculated(item, calculatedFields) {
112
238
  calculatedFields.forEach((calcField) => {
113
- if (calcField.name) {
114
- item[calcField.name] = typeof calcField.value === 'function' ? calcField.value(item) : calcField.value;
239
+ if (!calcField.name) {
240
+ this.logger.warn(`doCalculated: skipping entry with missing 'name' field`, calcField);
241
+ return;
115
242
  }
243
+ item[calcField.name] = typeof calcField.value === 'function' ? calcField.value(item) : calcField.value;
116
244
  });
117
245
  }
246
+ /**
247
+ * Executes a SELECT query with optional WHERE, whereIn, and query extension,
248
+ * then optionally maps results into a keyed object and/or applies
249
+ * calculated fields to each row.
250
+ *
251
+ * When `mapBy` is set, returns a `Record<string, row>` keyed by the
252
+ * camelCase value of `mapBy` field on each row, processed through
253
+ * `buildKey` (defaults to the `buildKey` from @sdflc/utils).
254
+ * When `mapBy` is not set, returns a plain array.
255
+ *
256
+ * @param args DatabaseReadInterface describing the query
257
+ */
118
258
  async read(args) {
119
- const { where, whereIn, extendQuery, table, selectFields, mapBy, calculated, buildKey } = args || {};
259
+ const { where, whereIn, extendQuery, table, selectFields, mapBy, calculated, buildKey: callerBuildKey, // renamed to avoid shadowing module-level buildKnexCacheKey
260
+ } = args || {};
120
261
  const query = this.getBuilder(table).select(Array.isArray(selectFields) && selectFields.length > 0 ? selectFields : '*');
121
262
  if (where) {
122
263
  query.where(where);
@@ -128,43 +269,58 @@ class Database {
128
269
  await extendQuery(query);
129
270
  }
130
271
  let dbResults = await query;
272
+ const hasCalculated = Array.isArray(calculated) && calculated.length > 0;
131
273
  if (mapBy) {
132
- const fnBuildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
274
+ const fnBuildKey = typeof callerBuildKey === 'function' ? callerBuildKey : utils_1.buildKey;
133
275
  dbResults = dbResults.reduce((acc, item) => {
134
- const key = fnBuildKey(item[(0, lodash_1.camelCase)(mapBy)]);
135
- if (Array.isArray(calculated) && calculated.length > 0) {
276
+ const key = fnBuildKey(item[(0, camelCase_1.default)(mapBy)]);
277
+ if (hasCalculated) {
136
278
  this.doCalculated(item, calculated);
137
279
  }
138
280
  acc[key] = item;
139
281
  return acc;
140
282
  }, {});
141
283
  }
142
- else {
143
- if (Array.isArray(calculated) && calculated.length > 0) {
144
- dbResults.forEach((row) => {
145
- this.doCalculated(row, calculated);
146
- });
147
- }
284
+ else if (hasCalculated) {
285
+ dbResults.forEach((row) => {
286
+ this.doCalculated(row, calculated);
287
+ });
148
288
  }
149
289
  return dbResults;
150
290
  }
291
+ /**
292
+ * Converts a sortBy array from the API params format into the Knex
293
+ * `orderBy` format `[{ column, order }]`.
294
+ *
295
+ * Falls back to `defaultSortBy` if `sortBy` is null/undefined.
296
+ * Returns null if neither is provided — callers should skip `orderBy()`
297
+ * when this returns null.
298
+ *
299
+ * @param sortBy Array of `{ name, order }` from request params
300
+ * @param defaultSortBy Fallback sort config from gateway config
301
+ */
151
302
  createSortBy(sortBy, defaultSortBy) {
152
303
  if (!sortBy) {
153
304
  if (Array.isArray(defaultSortBy)) {
154
305
  return this.createSortBy(defaultSortBy);
155
306
  }
156
- else {
157
- return null;
158
- }
307
+ return null;
159
308
  }
160
309
  return sortBy.reduce((acc, item) => {
161
- acc.push({
162
- column: item.name,
163
- order: item.order,
164
- });
310
+ acc.push({ column: item.name, order: item.order });
165
311
  return acc;
166
312
  }, []);
167
313
  }
314
+ /**
315
+ * Calculates `limit` and `offset` values from page/pageSize pagination params.
316
+ *
317
+ * Page is 1-indexed — page 1 with pageSize 10 gives offset 0.
318
+ * If `pageSize` is absent or NaN, `limit` is undefined (no limit applied).
319
+ * If `page` is absent, NaN, or < 1, it defaults to 1.
320
+ *
321
+ * @param page 1-based page number
322
+ * @param pageSize Number of records per page
323
+ */
168
324
  createLimitOffset(page, pageSize) {
169
325
  const limit = isNaN(pageSize) || pageSize == null ? undefined : Number(pageSize);
170
326
  const pageToUse = isNaN(page) || page < 1 ? 1 : Number(page);
@@ -173,19 +329,36 @@ class Database {
173
329
  offset: limit ? (pageToUse - 1) * limit : 0,
174
330
  };
175
331
  }
332
+ /**
333
+ * Combines `createLimitOffset()` and `createSortBy()` into a single call,
334
+ * reading pagination and sorting from the standard request params shape:
335
+ * `{ pagination: { page, pageSize }, sortBy: [{ name, order }] }`.
336
+ *
337
+ * Returns `{ limit, offset, sortBy }` ready to be applied to a Knex query.
338
+ * `sortBy` may be null if no sort is configured — callers should skip
339
+ * `query.orderBy()` in that case.
340
+ *
341
+ * @param params Request params object (may be null/undefined)
342
+ * @param defaultSortBy Fallback sort config from gateway config
343
+ */
176
344
  createLimitOffsetSortBy(params, defaultSortBy) {
177
345
  const { pagination, sortBy } = params || {};
178
346
  const { page, pageSize } = pagination || {};
179
347
  const { limit, offset } = this.createLimitOffset(page, pageSize);
180
348
  const sortByToUse = this.createSortBy(sortBy, defaultSortBy);
181
- return {
182
- limit,
183
- offset,
184
- sortBy: sortByToUse,
185
- };
349
+ return { limit, offset, sortBy: sortByToUse };
186
350
  }
351
+ /**
352
+ * Destroys the shared Knex connection pool for the given config.
353
+ * Use on application shutdown or in tests that need to reset the pool.
354
+ *
355
+ * Static because the pool is module-level — no instance needed.
356
+ */
187
357
  static destroyHandle(props) {
188
- const cfgKey = buildKey({ connection: props.knexConfig.connection, dbSchema: props.dbSchema });
358
+ const cfgKey = buildKnexCacheKey({
359
+ connection: props.knexConfig.connection,
360
+ dbSchema: props.dbSchema,
361
+ });
189
362
  if (knexHandles[cfgKey]) {
190
363
  knexHandles[cfgKey].destroy();
191
364
  delete knexHandles[cfgKey];