@sdflc/backend-helpers 1.0.111 → 1.0.113

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