@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,41 +1,164 @@
1
+ /**
2
+ * RedisDataLoader wraps Facebook's DataLoader with a Redis backing store,
3
+ * providing shared cross-request caching with optional TTL support.
4
+ *
5
+ * On cache miss, the provided `userLoader` is called to fetch the data,
6
+ * which is then written to Redis and returned. Subsequent requests for
7
+ * the same key are served directly from Redis without calling `userLoader`.
8
+ *
9
+ * Key namespacing:
10
+ * All Redis keys are prefixed with `keySpace:` to prevent collisions
11
+ * between different data sets in the same Redis instance.
12
+ *
13
+ * Serialisation:
14
+ * Values are serialised to JSON before storage (or via a custom
15
+ * `serialize` function) and deserialised on read (or via `deserialize`).
16
+ * Null values are stored as empty string '' to distinguish "cached null"
17
+ * from "cache miss" (which Redis returns as null).
18
+ */
1
19
  declare class RedisDataLoader {
2
- private opt?;
3
- private dataLoaderOpt?;
20
+ private opt;
21
+ private dataLoaderOpt;
4
22
  private keySpace;
5
- private loader?;
23
+ private loader;
6
24
  private redisClient;
7
25
  private static messages;
8
26
  constructor(redisClient: any, keySpace?: string, userLoader?: any, opt?: any);
9
27
  /**
10
- * Adds a prefix to the passed key
11
- * @param key Key value
12
- * @returns Trasnformed key value that includes key space
28
+ * Builds a namespaced Redis key from the raw key.
29
+ * Applies `cacheKeyFn` then prepends the keySpace prefix.
30
+ *
31
+ * @param key Raw cache key (string or object)
13
32
  */
14
- makeKey(key: string): string;
33
+ makeKey(key: any): string;
15
34
  /**
16
- * Deserializes response from Readis
17
- * @param str String to deserialize
18
- * @returns
35
+ * Deserialises a Redis response value.
36
+ * Returns the value as-is if it is empty string or null (null = cached null).
37
+ * Uses a custom `deserialize` function if provided, otherwise `JSON.parse`.
38
+ *
39
+ * @param str Raw string value from Redis
19
40
  */
20
41
  parse(str: any): Promise<any>;
21
42
  /**
22
- * Serializes passed value to a string
23
- * @param value A value to be serialized
24
- * @returns serialized value in the form of string
43
+ * Serialises a value for storage in Redis.
44
+ * Null is stored as '' to distinguish "cached null" from "cache miss".
45
+ * Uses a custom `serialize` function if provided.
46
+ * Objects and primitives are serialised via JSON.stringify.
47
+ *
48
+ * Fix: previously threw for non-object, non-null values — primitives
49
+ * (numbers, booleans, strings) are now serialised as JSON instead.
50
+ *
51
+ * @param value Value to serialise
25
52
  */
26
53
  toString(value: any): Promise<string>;
54
+ /**
55
+ * Writes a single key-value pair to Redis and returns the stored value.
56
+ * Uses a Redis MULTI transaction to SET, optionally EXPIRE, then GET
57
+ * in a single round-trip.
58
+ *
59
+ * @param key Raw (unprefixed) cache key
60
+ * @param rawValue Value to store (will be serialised)
61
+ */
27
62
  rSetAndGet(key: string, rawValue: any): Promise<any>;
63
+ /**
64
+ * Writes multiple key-value pairs to Redis in a single MULTI transaction
65
+ * and returns the stored values via MGET.
66
+ *
67
+ * Fix: `makeKey` is synchronous — removed unnecessary `mapPromise` wrapper.
68
+ *
69
+ * @param keys Array of raw (unprefixed) cache keys
70
+ * @param rawValues Array of values to store (will be serialised)
71
+ */
28
72
  rMSetAndGet(keys: string[], rawValues: any[]): Promise<any[]>;
73
+ /**
74
+ * Reads a single value from Redis by key.
75
+ *
76
+ * @param key Raw (unprefixed) cache key
77
+ */
29
78
  rGet(key: string): Promise<any>;
79
+ /**
80
+ * Reads multiple values from Redis in a single MGET call.
81
+ *
82
+ * @param keys Array of raw (unprefixed) cache keys
83
+ */
30
84
  rMGet(keys: string[]): Promise<any[]>;
31
- rSet(key: string, rawValue: any): Promise<any>;
85
+ /**
86
+ * Writes a single key-value pair to Redis.
87
+ * Returns the raw Redis reply ('OK') — no parsing needed for SET replies.
88
+ *
89
+ * Fix: was calling `this.parse(reply)` on the SET reply — Redis SET returns
90
+ * 'OK' which is not valid JSON and would throw a SyntaxError.
91
+ *
92
+ * @param key Raw (unprefixed) cache key
93
+ * @param rawValue Value to store (will be serialised)
94
+ */
95
+ rSet(key: string, rawValue: any): Promise<string>;
96
+ /**
97
+ * Writes multiple key-value pairs to Redis using MSET.
98
+ * Optionally sets expiry on each key.
99
+ *
100
+ * Fix: was calling `multi.expire(key, ...)` with the raw key — now
101
+ * correctly uses `makeKey(key)` to apply the namespace prefix.
102
+ *
103
+ * @param keys Array of raw (unprefixed) cache keys
104
+ * @param values Array of pre-serialised string values
105
+ */
32
106
  rMSet(keys: string[], values: any[]): Promise<any>;
33
- rDel(key: string): Promise<any>;
34
- load(key: string): Promise<any>;
35
- loadMany(keys: string[]): Promise<any>;
36
- prime(key: string, value: any): Promise<any>;
37
- clear(key: string): Promise<any>;
38
- clearAllLocal(): Promise<any>;
39
- clearLocal(key: string): Promise<any>;
107
+ /**
108
+ * Deletes a single key from Redis.
109
+ *
110
+ * @param key Raw (unprefixed) cache key
111
+ */
112
+ rDel(key: string): Promise<number>;
113
+ /**
114
+ * Loads a single value via DataLoader (Redis-backed with in-memory dedup).
115
+ * Batches concurrent calls within the same tick.
116
+ *
117
+ * Fix: was using `!key` which rejects 0 as a valid integer key.
118
+ * Now uses `key == null` to only reject null/undefined.
119
+ *
120
+ * @param key Cache key
121
+ */
122
+ load(key: any): Promise<any>;
123
+ /**
124
+ * Loads multiple values via DataLoader in a single batched call.
125
+ * Results are returned in the same order as the input keys.
126
+ *
127
+ * @param keys Array of cache keys
128
+ */
129
+ loadMany(keys: any[]): Promise<any[]>;
130
+ /**
131
+ * Primes the cache with a known value — writes to Redis and seeds
132
+ * the DataLoader in-memory cache to avoid a round-trip on the next load().
133
+ *
134
+ * Fix: was using raw `key` in DataLoader cache operations — now uses
135
+ * `makeKey(key)` to match the key format used internally by `load()`.
136
+ *
137
+ * @param key Cache key
138
+ * @param value Value to cache
139
+ */
140
+ prime(key: any, value: any): Promise<any>;
141
+ /**
142
+ * Removes a key from Redis and clears it from the DataLoader in-memory cache.
143
+ *
144
+ * Fix: was using raw `key` in `this.loader.clear()` — now uses `makeKey(key)`
145
+ * to match the key format used internally by `load()`.
146
+ *
147
+ * @param key Cache key
148
+ */
149
+ clear(key: any): Promise<number>;
150
+ /**
151
+ * Clears all entries from the DataLoader in-memory cache.
152
+ * Does NOT clear Redis — only the local request-level dedup cache.
153
+ * Use `rDel` or Redis FLUSHDB for full cache invalidation.
154
+ */
155
+ clearAllLocal(): Promise<void>;
156
+ /**
157
+ * Clears a single key from the DataLoader in-memory cache only.
158
+ * Does NOT delete from Redis.
159
+ *
160
+ * @param key Cache key (will have makeKey applied)
161
+ */
162
+ clearLocal(key: any): Promise<void>;
40
163
  }
41
164
  export { RedisDataLoader };
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/RedisDataLoader.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
@@ -7,8 +8,33 @@ exports.RedisDataLoader = void 0;
7
8
  const lodash_1 = require("lodash");
8
9
  const dataloader_1 = __importDefault(require("dataloader"));
9
10
  const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
11
+ /**
12
+ * Options specific to RedisDataLoader — not passed through to DataLoader.
13
+ */
10
14
  const customOptions = ['expire', 'serialize', 'deserialize', 'cacheKeyFn'];
11
- const mapPromise = (promise, fn) => Promise.all(promise.map(fn));
15
+ /**
16
+ * Convenience wrapper around Promise.all + Array.map.
17
+ * Resolves an array of promises returned by `fn` applied to each item.
18
+ */
19
+ const mapPromise = (items, fn) => Promise.all(items.map(fn));
20
+ /**
21
+ * RedisDataLoader wraps Facebook's DataLoader with a Redis backing store,
22
+ * providing shared cross-request caching with optional TTL support.
23
+ *
24
+ * On cache miss, the provided `userLoader` is called to fetch the data,
25
+ * which is then written to Redis and returned. Subsequent requests for
26
+ * the same key are served directly from Redis without calling `userLoader`.
27
+ *
28
+ * Key namespacing:
29
+ * All Redis keys are prefixed with `keySpace:` to prevent collisions
30
+ * between different data sets in the same Redis instance.
31
+ *
32
+ * Serialisation:
33
+ * Values are serialised to JSON before storage (or via a custom
34
+ * `serialize` function) and deserialised on read (or via `deserialize`).
35
+ * Null values are stored as empty string '' to distinguish "cached null"
36
+ * from "cache miss" (which Redis returns as null).
37
+ */
12
38
  class RedisDataLoader {
13
39
  opt;
14
40
  dataLoaderOpt;
@@ -20,7 +46,7 @@ class RedisDataLoader {
20
46
  keysArrayRequired: 'The "keys" parameter is required and should be an array',
21
47
  valueRequired: 'The "value" parameter is required',
22
48
  valueObjectOrNull: 'The "value" parameter must be an object or null',
23
- keysValuesLengths: 'The "keys" and "values" are expected to be the same',
49
+ keysValuesLengths: 'The "keys" and "values" are expected to be the same length',
24
50
  };
25
51
  constructor(redisClient, keySpace, userLoader, opt) {
26
52
  this.redisClient = redisClient;
@@ -29,15 +55,18 @@ class RedisDataLoader {
29
55
  ...(0, lodash_1.omit)(opt, customOptions),
30
56
  cacheKeyFn: this.opt.cacheKeyFn,
31
57
  };
58
+ // Default cache key function: stringify objects for stable key generation,
59
+ // pass primitive keys through as-is
32
60
  this.opt.cacheKeyFn =
33
61
  typeof this.opt.cacheKeyFn === 'function'
34
62
  ? this.opt.cacheKeyFn
35
63
  : (key) => ((0, lodash_1.isObject)(key) ? (0, json_stable_stringify_1.default)(key) : key);
36
- this.keySpace = keySpace ? keySpace + ':' : '';
64
+ this.keySpace = keySpace ? `${keySpace}:` : '';
37
65
  this.loader = new dataloader_1.default(async (keys) => {
38
66
  const results = await this.rMGet(keys);
39
67
  const keysToRead = [];
40
68
  const keysIdxsToRead = [];
69
+ // Collect cache misses (null = not in Redis yet)
41
70
  keys.forEach((key, idx) => {
42
71
  if (results[idx] == null) {
43
72
  keysToRead.push(key);
@@ -47,6 +76,7 @@ class RedisDataLoader {
47
76
  if (keysToRead.length > 0) {
48
77
  const loadedData = await userLoader.load(keysToRead);
49
78
  const data = await this.rMSetAndGet(keysToRead, loadedData);
79
+ // Merge loaded data back into the results array at the correct positions
50
80
  keysIdxsToRead.forEach((keyIdx, idx) => {
51
81
  results[keyIdx] = data[idx];
52
82
  });
@@ -55,17 +85,20 @@ class RedisDataLoader {
55
85
  }, this.dataLoaderOpt);
56
86
  }
57
87
  /**
58
- * Adds a prefix to the passed key
59
- * @param key Key value
60
- * @returns Trasnformed key value that includes key space
88
+ * Builds a namespaced Redis key from the raw key.
89
+ * Applies `cacheKeyFn` then prepends the keySpace prefix.
90
+ *
91
+ * @param key Raw cache key (string or object)
61
92
  */
62
93
  makeKey(key) {
63
94
  return `${this.keySpace}${this.opt.cacheKeyFn(key)}`;
64
95
  }
65
96
  /**
66
- * Deserializes response from Readis
67
- * @param str String to deserialize
68
- * @returns
97
+ * Deserialises a Redis response value.
98
+ * Returns the value as-is if it is empty string or null (null = cached null).
99
+ * Uses a custom `deserialize` function if provided, otherwise `JSON.parse`.
100
+ *
101
+ * @param str Raw string value from Redis
69
102
  */
70
103
  async parse(str) {
71
104
  if (str === '' || str === null) {
@@ -79,9 +112,15 @@ class RedisDataLoader {
79
112
  }
80
113
  }
81
114
  /**
82
- * Serializes passed value to a string
83
- * @param value A value to be serialized
84
- * @returns serialized value in the form of string
115
+ * Serialises a value for storage in Redis.
116
+ * Null is stored as '' to distinguish "cached null" from "cache miss".
117
+ * Uses a custom `serialize` function if provided.
118
+ * Objects and primitives are serialised via JSON.stringify.
119
+ *
120
+ * Fix: previously threw for non-object, non-null values — primitives
121
+ * (numbers, booleans, strings) are now serialised as JSON instead.
122
+ *
123
+ * @param value Value to serialise
85
124
  */
86
125
  async toString(value) {
87
126
  if (value === null) {
@@ -90,13 +129,20 @@ class RedisDataLoader {
90
129
  else if (typeof this.opt.serialize === 'function') {
91
130
  return await this.opt.serialize(value);
92
131
  }
93
- else if ((0, lodash_1.isObject)(value)) {
94
- return JSON.stringify(value);
95
- }
96
132
  else {
97
- throw new Error(RedisDataLoader.messages.valueObjectOrNull);
133
+ // Fix: was throwing for non-object values — primitives are valid
134
+ // cacheable values and should be serialised as JSON
135
+ return JSON.stringify(value);
98
136
  }
99
137
  }
138
+ /**
139
+ * Writes a single key-value pair to Redis and returns the stored value.
140
+ * Uses a Redis MULTI transaction to SET, optionally EXPIRE, then GET
141
+ * in a single round-trip.
142
+ *
143
+ * @param key Raw (unprefixed) cache key
144
+ * @param rawValue Value to store (will be serialised)
145
+ */
100
146
  async rSetAndGet(key, rawValue) {
101
147
  const value = await this.toString(rawValue);
102
148
  const fullKey = this.makeKey(key);
@@ -108,12 +154,21 @@ class RedisDataLoader {
108
154
  multi.get(fullKey);
109
155
  const replies = await multi.exec();
110
156
  const lastReply = (0, lodash_1.last)(replies);
111
- const result = await this.parse(lastReply);
112
- return result;
157
+ return this.parse(lastReply);
113
158
  }
159
+ /**
160
+ * Writes multiple key-value pairs to Redis in a single MULTI transaction
161
+ * and returns the stored values via MGET.
162
+ *
163
+ * Fix: `makeKey` is synchronous — removed unnecessary `mapPromise` wrapper.
164
+ *
165
+ * @param keys Array of raw (unprefixed) cache keys
166
+ * @param rawValues Array of values to store (will be serialised)
167
+ */
114
168
  async rMSetAndGet(keys, rawValues) {
115
169
  const multi = this.redisClient.multi();
116
- const fullKeys = await mapPromise(keys, (key) => this.makeKey(key));
170
+ // Fix: makeKey is sync — no need to wrap in mapPromise/Promise.all
171
+ const fullKeys = keys.map((key) => this.makeKey(key));
117
172
  const values = await mapPromise(rawValues, (rawValue) => this.toString(rawValue));
118
173
  multi.mSet(fullKeys.reduce((acc, fullKey, idx) => {
119
174
  acc.push(fullKey);
@@ -128,28 +183,52 @@ class RedisDataLoader {
128
183
  multi.mGet(fullKeys);
129
184
  const replies = await multi.exec();
130
185
  const lastReplies = (0, lodash_1.last)(replies);
131
- const result = await mapPromise(lastReplies, (lastReply) => this.parse(lastReply));
132
- return result;
186
+ return mapPromise(lastReplies, (lastReply) => this.parse(lastReply));
133
187
  }
188
+ /**
189
+ * Reads a single value from Redis by key.
190
+ *
191
+ * @param key Raw (unprefixed) cache key
192
+ */
134
193
  async rGet(key) {
135
194
  const reply = await this.redisClient.get(this.makeKey(key));
136
- const result = await this.parse(reply);
137
- return result;
195
+ return this.parse(reply);
138
196
  }
197
+ /**
198
+ * Reads multiple values from Redis in a single MGET call.
199
+ *
200
+ * @param keys Array of raw (unprefixed) cache keys
201
+ */
139
202
  async rMGet(keys) {
140
- const replies = await this.redisClient.mGet((0, lodash_1.map)(keys, (key) => this.makeKey(key)));
141
- const results = await mapPromise(replies, (reply) => this.parse(reply));
142
- return results;
203
+ const replies = await this.redisClient.mGet(keys.map((key) => this.makeKey(key)));
204
+ return mapPromise(replies, (reply) => this.parse(reply));
143
205
  }
206
+ /**
207
+ * Writes a single key-value pair to Redis.
208
+ * Returns the raw Redis reply ('OK') — no parsing needed for SET replies.
209
+ *
210
+ * Fix: was calling `this.parse(reply)` on the SET reply — Redis SET returns
211
+ * 'OK' which is not valid JSON and would throw a SyntaxError.
212
+ *
213
+ * @param key Raw (unprefixed) cache key
214
+ * @param rawValue Value to store (will be serialised)
215
+ */
144
216
  async rSet(key, rawValue) {
145
217
  const value = await this.toString(rawValue);
146
- const reply = await this.redisClient.set(this.makeKey(key), value);
147
- const result = await this.parse(reply);
148
- // result is expected to be OK
149
- return result;
218
+ return this.redisClient.set(this.makeKey(key), value);
150
219
  }
220
+ /**
221
+ * Writes multiple key-value pairs to Redis using MSET.
222
+ * Optionally sets expiry on each key.
223
+ *
224
+ * Fix: was calling `multi.expire(key, ...)` with the raw key — now
225
+ * correctly uses `makeKey(key)` to apply the namespace prefix.
226
+ *
227
+ * @param keys Array of raw (unprefixed) cache keys
228
+ * @param values Array of pre-serialised string values
229
+ */
151
230
  async rMSet(keys, values) {
152
- if (keys.length != values.length) {
231
+ if (keys.length !== values.length) {
153
232
  throw new Error(RedisDataLoader.messages.keysValuesLengths);
154
233
  }
155
234
  const multi = this.redisClient.multi();
@@ -160,53 +239,103 @@ class RedisDataLoader {
160
239
  }, []));
161
240
  if (this.opt.expire) {
162
241
  for (const key of keys) {
163
- multi.expire(key, this.opt.expire);
242
+ // Fix: was using raw `key` — must use makeKey to apply namespace prefix
243
+ multi.expire(this.makeKey(key), this.opt.expire);
164
244
  }
165
245
  }
166
- // The reply is expected to be "OK"
167
- const reply = await multi.exec();
168
- return reply;
246
+ return multi.exec();
169
247
  }
248
+ /**
249
+ * Deletes a single key from Redis.
250
+ *
251
+ * @param key Raw (unprefixed) cache key
252
+ */
170
253
  async rDel(key) {
171
- return await this.redisClient.del(this.makeKey(key));
254
+ return this.redisClient.del(this.makeKey(key));
172
255
  }
256
+ /**
257
+ * Loads a single value via DataLoader (Redis-backed with in-memory dedup).
258
+ * Batches concurrent calls within the same tick.
259
+ *
260
+ * Fix: was using `!key` which rejects 0 as a valid integer key.
261
+ * Now uses `key == null` to only reject null/undefined.
262
+ *
263
+ * @param key Cache key
264
+ */
173
265
  async load(key) {
174
- if (!key) {
266
+ if (key == null) {
175
267
  throw new TypeError(RedisDataLoader.messages.keyRequired);
176
268
  }
177
- return await this.loader.load(key);
269
+ return this.loader.load(key);
178
270
  }
271
+ /**
272
+ * Loads multiple values via DataLoader in a single batched call.
273
+ * Results are returned in the same order as the input keys.
274
+ *
275
+ * @param keys Array of cache keys
276
+ */
179
277
  async loadMany(keys) {
180
278
  if (!Array.isArray(keys)) {
181
279
  throw new TypeError(RedisDataLoader.messages.keysArrayRequired);
182
280
  }
183
- return await this.loader.loadMany(keys);
281
+ return this.loader.loadMany(keys);
184
282
  }
283
+ /**
284
+ * Primes the cache with a known value — writes to Redis and seeds
285
+ * the DataLoader in-memory cache to avoid a round-trip on the next load().
286
+ *
287
+ * Fix: was using raw `key` in DataLoader cache operations — now uses
288
+ * `makeKey(key)` to match the key format used internally by `load()`.
289
+ *
290
+ * @param key Cache key
291
+ * @param value Value to cache
292
+ */
185
293
  async prime(key, value) {
186
- if (!key) {
294
+ if (key == null) {
187
295
  throw new TypeError(RedisDataLoader.messages.keyRequired);
188
296
  }
189
- else if (value === undefined) {
297
+ if (value === undefined) {
190
298
  throw new TypeError(RedisDataLoader.messages.valueRequired);
191
299
  }
192
- else {
193
- const result = await this.rSetAndGet(key, value);
194
- return await this.loader.clear(key).prime(key, result === '' ? null : result);
195
- }
300
+ const result = await this.rSetAndGet(key, value);
301
+ const fullKey = this.makeKey(key);
302
+ // Fix: was using raw key in DataLoader cache — must use fullKey to match
303
+ // the key format that load() uses internally
304
+ return this.loader.clear(fullKey).prime(fullKey, result === '' ? null : result);
196
305
  }
306
+ /**
307
+ * Removes a key from Redis and clears it from the DataLoader in-memory cache.
308
+ *
309
+ * Fix: was using raw `key` in `this.loader.clear()` — now uses `makeKey(key)`
310
+ * to match the key format used internally by `load()`.
311
+ *
312
+ * @param key Cache key
313
+ */
197
314
  async clear(key) {
198
- if (!key) {
315
+ if (key == null) {
199
316
  throw new TypeError(RedisDataLoader.messages.keyRequired);
200
317
  }
201
318
  const resp = await this.rDel(key);
202
- await this.loader.clear(key);
319
+ // Fix: was using raw key — must use fullKey to match load() key format
320
+ this.loader.clear(this.makeKey(key));
203
321
  return resp;
204
322
  }
323
+ /**
324
+ * Clears all entries from the DataLoader in-memory cache.
325
+ * Does NOT clear Redis — only the local request-level dedup cache.
326
+ * Use `rDel` or Redis FLUSHDB for full cache invalidation.
327
+ */
205
328
  async clearAllLocal() {
206
- return await this.loader.clearAll();
329
+ return this.loader.clearAll();
207
330
  }
331
+ /**
332
+ * Clears a single key from the DataLoader in-memory cache only.
333
+ * Does NOT delete from Redis.
334
+ *
335
+ * @param key Cache key (will have makeKey applied)
336
+ */
208
337
  async clearLocal(key) {
209
- return await this.loader.clear(key);
338
+ return this.loader.clear(this.makeKey(key));
210
339
  }
211
340
  }
212
341
  exports.RedisDataLoader = RedisDataLoader;
@@ -1,11 +1,3 @@
1
1
  import { ApiContext, ApiContextInterface } from './interfaces';
2
- /**
3
- * Creates a GraphQL context object with all available cores.
4
- * @returns {object} A context object with all available cores
5
- */
6
2
  export declare const createApiContext: (args: ApiContextInterface) => Promise<ApiContext>;
7
- /**
8
- * Creates default a GraphQL context object with all avilable cores.
9
- * @returns {object} A context object with all available cores
10
- */
11
3
  export declare const createContextDefault: (args: any) => Promise<ApiContext>;
@@ -4,16 +4,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createContextDefault = exports.createApiContext = void 0;
7
+ // ./src/apiContext.ts
7
8
  const lodash_1 = require("lodash");
8
9
  const uuid_1 = require("uuid");
9
10
  const check_types_1 = __importDefault(require("check-types"));
10
11
  const utils_1 = require("@sdflc/utils");
11
12
  const Database_1 = require("./Database");
12
13
  const constants_1 = require("./constants");
13
- /**
14
- * Creates a GraphQL context object with all available cores.
15
- * @returns {object} A context object with all available cores
16
- */
14
+ const resolveClientIp_1 = require("./resolveClientIp");
17
15
  const createApiContext = async (args) => {
18
16
  const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
19
17
  const requestId = inRequestId || (0, uuid_1.v4)();
@@ -32,10 +30,7 @@ const createApiContext = async (args) => {
32
30
  return acc;
33
31
  }, {});
34
32
  context.gateways = Object.keys(gateways || {}).reduce((acc, key) => {
35
- acc[(0, lodash_1.camelCase)(key)] = new gateways[key]({
36
- ...gatewayContext,
37
- context,
38
- });
33
+ acc[(0, lodash_1.camelCase)(key)] = new gateways[key]({ ...gatewayContext, context });
39
34
  return acc;
40
35
  }, {});
41
36
  if (check_types_1.default.function(extendContext)) {
@@ -44,10 +39,6 @@ const createApiContext = async (args) => {
44
39
  return context;
45
40
  };
46
41
  exports.createApiContext = createApiContext;
47
- /**
48
- * Creates default a GraphQL context object with all avilable cores.
49
- * @returns {object} A context object with all available cores
50
- */
51
42
  const createContextDefault = async (args) => {
52
43
  const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
53
44
  const headers = req.headers || { noHeadersSetup: true };
@@ -59,18 +50,16 @@ const createContextDefault = async (args) => {
59
50
  const managementApiKey = headers[constants_1.HEADERS.MANAGEMENT_API_KEY];
60
51
  const userAgent = headers[constants_1.HEADERS.USER_AGENT];
61
52
  const referer = headers[constants_1.HEADERS.REFERER];
62
- const ipAddress = headers[constants_1.HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
53
+ // req.connection was removed in Node.js v19 — use req.socket instead
54
+ const ipAddress = (0, resolveClientIp_1.resolveClientIp)(headers, req);
63
55
  const acceptLanguage = headers[constants_1.HEADERS.ACCEPT_LANGUAGE];
64
56
  const languages = (0, utils_1.extractLanguages)(acceptLanguage);
65
57
  const requestedLang = headers[constants_1.HEADERS.REQUESTED_LANGUAGE] || languages?.[0] || 'en';
66
- // const accountId = headers[HEADERS.ACCOUNT_ID];
67
- // const roleId = headers[HEADERS.ROLE_ID];
68
- // const userId = headers[HEADERS.USER_ID];
69
58
  const requestId = (0, uuid_1.v4)();
70
59
  const db = inDb
71
60
  ? inDb
72
61
  : new Database_1.Database({
73
- dbType: dbType || knexConfig.client || '',
62
+ dbType: dbType || knexConfig?.client || '',
74
63
  knexConfig,
75
64
  dbSchema,
76
65
  logger,
@@ -87,9 +76,6 @@ const createContextDefault = async (args) => {
87
76
  requestedLang,
88
77
  authorization,
89
78
  fingerprint,
90
- // accountId,
91
- // roleId,
92
- // userId,
93
79
  req,
94
80
  res,
95
81
  headers,
@@ -111,10 +97,9 @@ const createContextDefault = async (args) => {
111
97
  }
112
98
  },
113
99
  getCoreContext: async (args) => {
114
- // TODO: const { req } = args;
115
- let extendCoreConext = {};
100
+ let extendCoreContext = {}; // fixed typo: extendCoreConext → extendCoreContext
116
101
  if (check_types_1.default.function(getCoreContext)) {
117
- extendCoreConext = await getCoreContext(args);
102
+ extendCoreContext = await getCoreContext(args);
118
103
  }
119
104
  return {
120
105
  db,
@@ -126,19 +111,19 @@ const createContextDefault = async (args) => {
126
111
  interserviceApiKey,
127
112
  jwtSecret,
128
113
  verifyTokenArgs,
129
- ...(extendCoreConext || {}),
114
+ ...(extendCoreContext || {}),
130
115
  };
131
116
  },
132
117
  getGatewayContext: async (args) => {
133
- let extendGatewayConext = {};
118
+ let extendGatewayContext = {}; // fixed typo: extendGatewayConext → extendGatewayContext
134
119
  if (check_types_1.default.function(getGatewayContext)) {
135
- extendGatewayConext = await getGatewayContext(args);
120
+ extendGatewayContext = await getGatewayContext(args);
136
121
  }
137
122
  return {
138
123
  db,
139
124
  isProduction,
140
125
  logger,
141
- ...(extendGatewayConext || {}),
126
+ ...(extendGatewayContext || {}),
142
127
  };
143
128
  },
144
129
  });