@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
@@ -0,0 +1,37 @@
1
+ import { BaseController } from './BaseController';
2
+ import { BaseRestApiCrudControllerPropsInterface } from './interfaces';
3
+ declare class BaseRestApiCrudController extends BaseController {
4
+ protected coreToUse: string;
5
+ protected getContext: (req: any) => Promise<any> | any;
6
+ protected disableList: boolean;
7
+ protected disableGet: boolean;
8
+ protected disableGetMany: boolean;
9
+ protected disableCreate: boolean;
10
+ protected disableCreateMany: boolean;
11
+ protected disableUpdate: boolean;
12
+ protected disableUpdateMany: boolean;
13
+ protected disableRemove: boolean;
14
+ protected disableRemoveMany: boolean;
15
+ constructor(props: BaseRestApiCrudControllerPropsInterface);
16
+ protected resolveCore(req: any): Promise<any>;
17
+ init(props: {
18
+ app: any;
19
+ root: string;
20
+ }): void;
21
+ protected list(req: any): Promise<any>;
22
+ /**
23
+ * Handles GET /:id — routes to core.get() for a single id,
24
+ * or core.getMany() when the :id param contains commas.
25
+ */
26
+ protected getOrGetMany(req: any): Promise<any>;
27
+ protected create(req: any): Promise<any>;
28
+ protected createMany(req: any): Promise<any>;
29
+ protected update(req: any): Promise<any>;
30
+ protected updateMany(req: any): Promise<any>;
31
+ /**
32
+ * Handles DELETE /:id — routes to core.remove() for a single id,
33
+ * or core.removeMany() when the :id param contains commas.
34
+ */
35
+ protected removeOrRemoveMany(req: any): Promise<any>;
36
+ }
37
+ export { BaseRestApiCrudController };
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ // ./src/baseRestApiCrudController.ts
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.BaseRestApiCrudController = void 0;
5
+ const BaseController_1 = require("./BaseController");
6
+ const parseIds_1 = require("./parseIds");
7
+ class BaseRestApiCrudController extends BaseController_1.BaseController {
8
+ coreToUse;
9
+ getContext;
10
+ disableList;
11
+ disableGet;
12
+ disableGetMany;
13
+ disableCreate;
14
+ disableCreateMany;
15
+ disableUpdate;
16
+ disableUpdateMany;
17
+ disableRemove;
18
+ disableRemoveMany;
19
+ constructor(props) {
20
+ super(props);
21
+ const { prefix, core, getContext } = props || {};
22
+ if (!getContext) {
23
+ throw new Error('BaseRestApiCrudController: `getContext` is required');
24
+ }
25
+ this.coreToUse = core || `${prefix}Core`;
26
+ this.getContext = getContext;
27
+ this.disableList = props.disableList ?? false;
28
+ this.disableGet = props.disableGet ?? false;
29
+ this.disableGetMany = props.disableGetMany ?? false;
30
+ this.disableCreate = props.disableCreate ?? false;
31
+ this.disableCreateMany = props.disableCreateMany ?? false;
32
+ this.disableUpdate = props.disableUpdate ?? false;
33
+ this.disableUpdateMany = props.disableUpdateMany ?? false;
34
+ this.disableRemove = props.disableRemove ?? false;
35
+ this.disableRemoveMany = props.disableRemoveMany ?? false;
36
+ }
37
+ async resolveCore(req) {
38
+ const context = await this.getContext(req);
39
+ const core = context?.cores?.[this.coreToUse];
40
+ if (!core) {
41
+ throw new Error(`BaseRestApiCrudController: core "${this.coreToUse}" not found in context`);
42
+ }
43
+ return core;
44
+ }
45
+ init(props) {
46
+ const { app, root } = props || {};
47
+ if (!app || !root) {
48
+ throw new Error('BaseRestApiCrudController.init: `app` and `root` are required');
49
+ }
50
+ if (!this.disableList) {
51
+ app.get(root, this.json(this.list.bind(this)));
52
+ }
53
+ // GET /:id — branches to get() or getMany() based on comma presence
54
+ if (!this.disableGet || !this.disableGetMany) {
55
+ app.get(`${root}/:id`, this.json(this.getOrGetMany.bind(this)));
56
+ }
57
+ if (!this.disableCreate) {
58
+ app.post(root, this.json(this.create.bind(this)));
59
+ }
60
+ if (!this.disableCreateMany) {
61
+ app.post(`${root}/many`, this.json(this.createMany.bind(this)));
62
+ }
63
+ if (!this.disableUpdate) {
64
+ app.put(`${root}/:id`, this.json(this.update.bind(this)));
65
+ }
66
+ if (!this.disableUpdateMany) {
67
+ app.put(`${root}/many`, this.json(this.updateMany.bind(this)));
68
+ }
69
+ // DELETE /:id — branches to remove() or removeMany() based on comma presence
70
+ if (!this.disableRemove || !this.disableRemoveMany) {
71
+ app.delete(`${root}/:id`, this.json(this.removeOrRemoveMany.bind(this)));
72
+ }
73
+ }
74
+ // ─── Route handlers ────────────────────────────────────────────────────────
75
+ async list(req) {
76
+ const core = await this.resolveCore(req);
77
+ return core.list({ params: req.query });
78
+ }
79
+ /**
80
+ * Handles GET /:id — routes to core.get() for a single id,
81
+ * or core.getMany() when the :id param contains commas.
82
+ */
83
+ async getOrGetMany(req) {
84
+ const core = await this.resolveCore(req);
85
+ const [isSingle, ids] = (0, parseIds_1.parseIds)(req.params.id);
86
+ if (isSingle) {
87
+ if (this.disableGet) {
88
+ throw new Error(`GET by single id is disabled on this resource`);
89
+ }
90
+ return core.get({ params: { ...req.query, id: ids[0] } });
91
+ }
92
+ if (this.disableGetMany) {
93
+ throw new Error(`GET by multiple ids is disabled on this resource`);
94
+ }
95
+ return core.getMany({ params: { ...req.query, ids } });
96
+ }
97
+ async create(req) {
98
+ const core = await this.resolveCore(req);
99
+ return core.create({ params: req.body });
100
+ }
101
+ async createMany(req) {
102
+ const core = await this.resolveCore(req);
103
+ const items = Array.isArray(req.body) ? req.body : [req.body];
104
+ return core.createMany({ params: items });
105
+ }
106
+ async update(req) {
107
+ const core = await this.resolveCore(req);
108
+ return core.update({ params: { ...req.body, id: req.params.id } });
109
+ }
110
+ async updateMany(req) {
111
+ const core = await this.resolveCore(req);
112
+ const items = Array.isArray(req.body) ? req.body : [req.body];
113
+ return core.updateMany({ params: items });
114
+ }
115
+ /**
116
+ * Handles DELETE /:id — routes to core.remove() for a single id,
117
+ * or core.removeMany() when the :id param contains commas.
118
+ */
119
+ async removeOrRemoveMany(req) {
120
+ const core = await this.resolveCore(req);
121
+ const [isSingle, ids] = (0, parseIds_1.parseIds)(req.params.id);
122
+ if (isSingle) {
123
+ if (this.disableRemove) {
124
+ throw new Error(`DELETE by single id is disabled on this resource`);
125
+ }
126
+ return core.remove({ params: { id: ids[0] } });
127
+ }
128
+ if (this.disableRemoveMany) {
129
+ throw new Error(`DELETE by multiple ids is disabled on this resource`);
130
+ }
131
+ return core.removeMany({ params: { ids } });
132
+ }
133
+ }
134
+ exports.BaseRestApiCrudController = BaseRestApiCrudController;
@@ -1,16 +1,127 @@
1
- import { CacheInterface, LoaderInterface } from './interfaces';
1
+ import { DataCachePropsInterface, LoaderInterface } from './interfaces';
2
+ /**
3
+ * DataCache implements LoaderInterface using Facebook's DataLoader for
4
+ * batched, per-request in-memory caching of database records.
5
+ *
6
+ * It is the default loader used by BaseGateway when no custom loader is
7
+ * provided. Each DataCache instance is tied to a single request — DataLoader's
8
+ * cache is intentionally not shared across requests.
9
+ *
10
+ * Two backing strategies are supported:
11
+ * - In-memory DataLoader (default) — per-request cache, no TTL
12
+ * - Redis-backed RedisDataLoader — shared cache with TTL, used when
13
+ * `redisClient` is provided in config
14
+ *
15
+ * Key building:
16
+ * All cache keys are built via the `buildKey` function (defaults to
17
+ * `buildKey` from @sdflc/utils). This ensures consistent key format
18
+ * between `load()`, `loadMany()`, `prime()`, and `clear()` calls.
19
+ *
20
+ * Batch loading:
21
+ * By default, uses `batchLoaderDefault` which issues a single
22
+ * `WHERE idField IN (ids)` query per DataLoader tick. For `readAll: true`,
23
+ * fetches the entire table and maps by id field.
24
+ * A custom `loaderFn` can be provided to replace the default batch function.
25
+ */
2
26
  declare class DataCache implements LoaderInterface {
3
27
  private buildKey;
4
28
  private loader;
5
29
  private config;
6
30
  private redisClient;
7
- constructor(props: CacheInterface);
8
- batchLoaderDefault(props: CacheInterface): (ids: any[]) => Promise<any[]>;
31
+ constructor(props: DataCachePropsInterface);
32
+ /**
33
+ * Creates the default batch loader function for this DataCache instance.
34
+ *
35
+ * The returned async function is called by DataLoader with an array of
36
+ * keys collected during the current tick (batched). It issues a single
37
+ * `WHERE idField IN (ids)` query and maps results back to the input key
38
+ * order — DataLoader requires results in the same order as input keys,
39
+ * with `null` for any id that was not found.
40
+ *
41
+ * For `readAll: true`, fetches the entire table and returns all rows as
42
+ * a flat array rather than mapping by id.
43
+ *
44
+ * Throws synchronously (at DataCache construction time) if required config
45
+ * is missing — `table`, `idField` (unless `readAll` is set), and `db`.
46
+ *
47
+ * @param props DataCachePropsInterface config, already normalised with idField fallbacks
48
+ */
49
+ batchLoaderDefault(props: DataCachePropsInterface): (ids: any[]) => Promise<any[]>;
50
+ /**
51
+ * Initialises the underlying DataLoader or RedisDataLoader instance.
52
+ *
53
+ * When `redisClient` is available, uses RedisDataLoader for shared caching
54
+ * across requests with TTL support. The batch function is wrapped in a
55
+ * `{ load }` adapter since RedisDataLoader expects a DataLoader-like interface
56
+ * rather than a raw batch function.
57
+ *
58
+ * When no `redisClient` is available, uses a standard in-memory DataLoader.
59
+ * DataLoader's default options are used (unlimited batch size, caching enabled)
60
+ * which are appropriate for per-request instances.
61
+ *
62
+ * The `context` parameter is passed through to the batch function for use
63
+ * by custom `loaderFn` implementations — the default batch loader ignores it.
64
+ *
65
+ * @param batchFunction Async function receiving an array of keys, returning results in the same order
66
+ * @param keyPrefix Optional namespace prefix for Redis keys
67
+ * @param context Request context passed to the batch function
68
+ */
9
69
  init(batchFunction: any, keyPrefix?: string, context?: any): void;
10
- load(key: any): any;
11
- loadMany(keys: any[]): any;
70
+ /**
71
+ * Loads a single record by key.
72
+ *
73
+ * Returns null immediately if `key` is null or undefined — avoids
74
+ * passing invalid keys to the underlying loader or buildKey function.
75
+ *
76
+ * Fix: was checking `builtKey == null` after calling buildKey, but
77
+ * buildKey always returns a string (e.g. 'null') for null input.
78
+ * The guard now checks the input key directly.
79
+ *
80
+ * @param key The record id (before key building)
81
+ */
82
+ load(key: any): Promise<any>;
83
+ /**
84
+ * Loads multiple records by their keys in a single batched call.
85
+ *
86
+ * Null/undefined keys in the array are passed through as null rather
87
+ * than being sent to buildKey (which would produce a 'null' string key).
88
+ * DataLoader preserves result order, so null inputs produce null outputs
89
+ * at the same index.
90
+ *
91
+ * @param keys Array of record ids (before key building)
92
+ */
93
+ loadMany(keys: any[]): Promise<any[]>;
94
+ /**
95
+ * Primes the cache with a known value for the given key.
96
+ * Useful after a create() or update() to seed the cache without
97
+ * requiring a subsequent load() round-trip.
98
+ *
99
+ * Returns `this` for chaining.
100
+ *
101
+ * @param key The record id (before key building)
102
+ * @param value The value to cache
103
+ */
12
104
  prime(key: any, value: any): this;
105
+ /**
106
+ * Clears the cached value for one or more keys.
107
+ * Accepts either a single key or an array of keys.
108
+ *
109
+ * Called by BaseGateway after update(), updateMany(), increment(),
110
+ * decrement(), and remove() to ensure stale records are not served
111
+ * from cache on subsequent load() calls within the same request.
112
+ *
113
+ * Returns `this` for chaining.
114
+ *
115
+ * @param key A single record id or an array of record ids
116
+ */
13
117
  clear(key: any | any[]): this;
118
+ /**
119
+ * Clears all cached values from the loader.
120
+ * Rarely needed in normal operation — useful in tests or when a bulk
121
+ * operation has invalidated an unknown set of records.
122
+ *
123
+ * Returns `this` for chaining.
124
+ */
14
125
  clearAll(): this;
15
126
  }
16
127
  export { DataCache };
@@ -1,14 +1,39 @@
1
1
  "use strict";
2
+ // ./src/DataCache.ts
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.DataCache = void 0;
7
8
  const dataloader_1 = __importDefault(require("dataloader"));
8
- const RedisDataLoader_1 = require("./RedisDataLoader");
9
- const utils_1 = require("@sdflc/utils");
10
- const _1 = require(".");
11
9
  const lodash_1 = require("lodash");
10
+ const utils_1 = require("@sdflc/utils");
11
+ const RedisDataLoader_1 = require("./RedisDataLoader");
12
+ const constants_1 = require("./constants");
13
+ /**
14
+ * DataCache implements LoaderInterface using Facebook's DataLoader for
15
+ * batched, per-request in-memory caching of database records.
16
+ *
17
+ * It is the default loader used by BaseGateway when no custom loader is
18
+ * provided. Each DataCache instance is tied to a single request — DataLoader's
19
+ * cache is intentionally not shared across requests.
20
+ *
21
+ * Two backing strategies are supported:
22
+ * - In-memory DataLoader (default) — per-request cache, no TTL
23
+ * - Redis-backed RedisDataLoader — shared cache with TTL, used when
24
+ * `redisClient` is provided in config
25
+ *
26
+ * Key building:
27
+ * All cache keys are built via the `buildKey` function (defaults to
28
+ * `buildKey` from @sdflc/utils). This ensures consistent key format
29
+ * between `load()`, `loadMany()`, `prime()`, and `clear()` calls.
30
+ *
31
+ * Batch loading:
32
+ * By default, uses `batchLoaderDefault` which issues a single
33
+ * `WHERE idField IN (ids)` query per DataLoader tick. For `readAll: true`,
34
+ * fetches the entire table and maps by id field.
35
+ * A custom `loaderFn` can be provided to replace the default batch function.
36
+ */
12
37
  class DataCache {
13
38
  buildKey;
14
39
  loader;
@@ -16,29 +41,52 @@ class DataCache {
16
41
  redisClient;
17
42
  constructor(props) {
18
43
  const { loaderFn, keyPrefix, context, buildKey, redisClient, table } = props || {};
44
+ // Normalise idField and idFieldAs with fallbacks to the standard id field
19
45
  const innerProps = {
20
46
  ...props,
21
- idField: props?.idField || _1.FIELDS.ID,
22
- idFieldAs: props?.idFieldAs || _1.FIELDS.ID,
47
+ idField: props?.idField || constants_1.FIELDS.ID,
48
+ idFieldAs: props?.idFieldAs || constants_1.FIELDS.ID,
23
49
  };
24
50
  this.config = innerProps;
25
51
  this.redisClient = redisClient;
26
52
  this.buildKey = typeof buildKey === 'function' ? buildKey : utils_1.buildKey;
27
- this.batchLoaderDefault = this.batchLoaderDefault.bind(this);
53
+ // Use a custom loader function if provided, otherwise create the default
54
+ // batch loader. The default loader throws synchronously here if required
55
+ // config (table, idField, db) is missing — fail fast at construction time.
28
56
  const fn = typeof loaderFn === 'function' ? loaderFn : this.batchLoaderDefault(innerProps);
57
+ // keyPrefix scopes DataLoader cache keys to avoid collisions between
58
+ // different resources sharing the same Redis instance or request context.
59
+ // Resolution order: context.keyPrefix → config.keyPrefix → table name
29
60
  const prefixToUse = context?.keyPrefix || keyPrefix || table;
30
61
  this.init(fn, prefixToUse, context);
31
62
  }
63
+ /**
64
+ * Creates the default batch loader function for this DataCache instance.
65
+ *
66
+ * The returned async function is called by DataLoader with an array of
67
+ * keys collected during the current tick (batched). It issues a single
68
+ * `WHERE idField IN (ids)` query and maps results back to the input key
69
+ * order — DataLoader requires results in the same order as input keys,
70
+ * with `null` for any id that was not found.
71
+ *
72
+ * For `readAll: true`, fetches the entire table and returns all rows as
73
+ * a flat array rather than mapping by id.
74
+ *
75
+ * Throws synchronously (at DataCache construction time) if required config
76
+ * is missing — `table`, `idField` (unless `readAll` is set), and `db`.
77
+ *
78
+ * @param props DataCachePropsInterface config, already normalised with idField fallbacks
79
+ */
32
80
  batchLoaderDefault(props) {
33
81
  const { table, idField, idFieldAs, readAll, db } = props;
34
82
  if (!table) {
35
- throw Error(`DataCache requires 'table' property to be setup`);
83
+ throw new Error(`DataCache requires 'table' property to be set up`);
36
84
  }
37
- else if (!idField && readAll == null) {
38
- throw Error(`DataCache requires 'idField' or 'readAll' property to be setup`);
85
+ if (!idField && readAll == null) {
86
+ throw new Error(`DataCache requires 'idField' or 'readAll' property to be set up`);
39
87
  }
40
- else if (!db) {
41
- throw Error(`DataCache requires 'db' property to be setup`);
88
+ if (!db) {
89
+ throw new Error(`DataCache requires 'db' property to be set up`);
42
90
  }
43
91
  return async (ids) => {
44
92
  const resultItems = [];
@@ -48,29 +96,53 @@ class DataCache {
48
96
  };
49
97
  const idsToUse = (0, lodash_1.castArray)(ids);
50
98
  if (!readAll) {
99
+ // Map results by id so we can look them up in key order below.
100
+ // idFieldAs allows the query to alias the id column if it differs
101
+ // from the column name used for lookup (e.g. join scenarios).
51
102
  readCfg.mapBy = idFieldAs || idField;
52
103
  readCfg.whereIn = {
53
104
  field: idField,
54
- values: idsToUse.filter((id) => id),
105
+ // Fix: use != null instead of truthy check so integer id 0 is not filtered out
106
+ values: idsToUse.filter((id) => id != null),
55
107
  };
56
108
  }
57
109
  const dbItems = await db.read(readCfg);
58
110
  if (readAll) {
111
+ // readAll mode: no mapBy set so db.read() returns any[]
59
112
  resultItems.push(...dbItems);
60
113
  }
61
114
  else {
62
- resultItems.push(...idsToUse.map((id) => dbItems[this.buildKey(id)] || null));
115
+ // mapBy is set so db.read() returns Record<string, any>
116
+ const mappedItems = dbItems;
117
+ resultItems.push(...idsToUse.map((id) => mappedItems[this.buildKey(id)] || null));
63
118
  }
64
119
  return resultItems;
65
120
  };
66
121
  }
122
+ /**
123
+ * Initialises the underlying DataLoader or RedisDataLoader instance.
124
+ *
125
+ * When `redisClient` is available, uses RedisDataLoader for shared caching
126
+ * across requests with TTL support. The batch function is wrapped in a
127
+ * `{ load }` adapter since RedisDataLoader expects a DataLoader-like interface
128
+ * rather than a raw batch function.
129
+ *
130
+ * When no `redisClient` is available, uses a standard in-memory DataLoader.
131
+ * DataLoader's default options are used (unlimited batch size, caching enabled)
132
+ * which are appropriate for per-request instances.
133
+ *
134
+ * The `context` parameter is passed through to the batch function for use
135
+ * by custom `loaderFn` implementations — the default batch loader ignores it.
136
+ *
137
+ * @param batchFunction Async function receiving an array of keys, returning results in the same order
138
+ * @param keyPrefix Optional namespace prefix for Redis keys
139
+ * @param context Request context passed to the batch function
140
+ */
67
141
  init(batchFunction, keyPrefix, context) {
68
142
  if (this.redisClient) {
69
- this.loader = new RedisDataLoader_1.RedisDataLoader(this.redisClient,
70
- // set a prefix for the keys stored in redis. This way you can avoid key
71
- // collisions for different data-sets in your redis instance.
72
- keyPrefix,
73
- // create a regular loader. This should always be set with caching disabled.
143
+ this.loader = new RedisDataLoader_1.RedisDataLoader(this.redisClient, keyPrefix,
144
+ // RedisDataLoader expects a DataLoader-like object with a `load` method,
145
+ // not a raw batch function — wrap accordingly
74
146
  {
75
147
  load: (ids) => batchFunction(ids, context),
76
148
  }, {
@@ -82,20 +154,63 @@ class DataCache {
82
154
  this.loader = new dataloader_1.default((ids) => batchFunction(ids, context));
83
155
  }
84
156
  }
157
+ /**
158
+ * Loads a single record by key.
159
+ *
160
+ * Returns null immediately if `key` is null or undefined — avoids
161
+ * passing invalid keys to the underlying loader or buildKey function.
162
+ *
163
+ * Fix: was checking `builtKey == null` after calling buildKey, but
164
+ * buildKey always returns a string (e.g. 'null') for null input.
165
+ * The guard now checks the input key directly.
166
+ *
167
+ * @param key The record id (before key building)
168
+ */
85
169
  load(key) {
86
- const builtKey = this.buildKey(key);
87
- if (builtKey == null) {
170
+ if (key == null) {
88
171
  return Promise.resolve(null);
89
172
  }
90
- return this.loader.load(builtKey);
173
+ return this.loader.load(this.buildKey(key));
91
174
  }
175
+ /**
176
+ * Loads multiple records by their keys in a single batched call.
177
+ *
178
+ * Null/undefined keys in the array are passed through as null rather
179
+ * than being sent to buildKey (which would produce a 'null' string key).
180
+ * DataLoader preserves result order, so null inputs produce null outputs
181
+ * at the same index.
182
+ *
183
+ * @param keys Array of record ids (before key building)
184
+ */
92
185
  loadMany(keys) {
93
- return this.loader.loadMany(keys.map((key) => this.buildKey(key)));
186
+ return this.loader.loadMany(keys.map((key) => (key != null ? this.buildKey(key) : null)));
94
187
  }
188
+ /**
189
+ * Primes the cache with a known value for the given key.
190
+ * Useful after a create() or update() to seed the cache without
191
+ * requiring a subsequent load() round-trip.
192
+ *
193
+ * Returns `this` for chaining.
194
+ *
195
+ * @param key The record id (before key building)
196
+ * @param value The value to cache
197
+ */
95
198
  prime(key, value) {
96
199
  this.loader?.prime(this.buildKey(key), value);
97
200
  return this;
98
201
  }
202
+ /**
203
+ * Clears the cached value for one or more keys.
204
+ * Accepts either a single key or an array of keys.
205
+ *
206
+ * Called by BaseGateway after update(), updateMany(), increment(),
207
+ * decrement(), and remove() to ensure stale records are not served
208
+ * from cache on subsequent load() calls within the same request.
209
+ *
210
+ * Returns `this` for chaining.
211
+ *
212
+ * @param key A single record id or an array of record ids
213
+ */
99
214
  clear(key) {
100
215
  if (Array.isArray(key)) {
101
216
  key.forEach((item) => this.loader?.clear(this.buildKey(item)));
@@ -105,6 +220,13 @@ class DataCache {
105
220
  }
106
221
  return this;
107
222
  }
223
+ /**
224
+ * Clears all cached values from the loader.
225
+ * Rarely needed in normal operation — useful in tests or when a bulk
226
+ * operation has invalidated an unknown set of records.
227
+ *
228
+ * Returns `this` for chaining.
229
+ */
108
230
  clearAll() {
109
231
  this.loader?.clearAll();
110
232
  return this;