@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
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/apiContext.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
@@ -8,12 +9,10 @@ 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");
12
+ const IpRateLimiter_1 = require("./IpRateLimiter");
11
13
  const Database_1 = require("./Database");
12
14
  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
- */
15
+ const resolveClientIp_1 = require("./resolveClientIp");
17
16
  const createApiContext = async (args) => {
18
17
  const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
19
18
  const requestId = inRequestId || (0, uuid_1.v4)();
@@ -32,10 +31,7 @@ const createApiContext = async (args) => {
32
31
  return acc;
33
32
  }, {});
34
33
  context.gateways = Object.keys(gateways || {}).reduce((acc, key) => {
35
- acc[(0, lodash_1.camelCase)(key)] = new gateways[key]({
36
- ...gatewayContext,
37
- context,
38
- });
34
+ acc[(0, lodash_1.camelCase)(key)] = new gateways[key]({ ...gatewayContext, context });
39
35
  return acc;
40
36
  }, {});
41
37
  if (check_types_1.default.function(extendContext)) {
@@ -44,12 +40,12 @@ const createApiContext = async (args) => {
44
40
  return context;
45
41
  };
46
42
  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
43
  const createContextDefault = async (args) => {
52
- const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
44
+ const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb,
45
+ // Rate limiting — both optional. If redisClient is provided and no custom
46
+ // rateLimiter is given, a built-in IpRateLimiter is constructed here once
47
+ // and shared across every core for the lifetime of this context.
48
+ redisClient, rateLimiter: inRateLimiter, globalRateLimit, } = args || {};
53
49
  const headers = req.headers || { noHeadersSetup: true };
54
50
  const cookies = req.cookies || { noCookiesSetup: true };
55
51
  const authorization = (headers[constants_1.HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
@@ -59,22 +55,28 @@ const createContextDefault = async (args) => {
59
55
  const managementApiKey = headers[constants_1.HEADERS.MANAGEMENT_API_KEY];
60
56
  const userAgent = headers[constants_1.HEADERS.USER_AGENT];
61
57
  const referer = headers[constants_1.HEADERS.REFERER];
62
- const ipAddress = headers[constants_1.HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
58
+ // req.connection was removed in Node.js v19 — use req.socket instead
59
+ const ipAddress = (0, resolveClientIp_1.resolveClientIp)(headers, req);
63
60
  const acceptLanguage = headers[constants_1.HEADERS.ACCEPT_LANGUAGE];
64
61
  const languages = (0, utils_1.extractLanguages)(acceptLanguage);
65
62
  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
63
  const requestId = (0, uuid_1.v4)();
70
64
  const db = inDb
71
65
  ? inDb
72
66
  : new Database_1.Database({
73
- dbType: dbType || knexConfig.client || '',
67
+ dbType: dbType || knexConfig?.client || '',
74
68
  knexConfig,
75
69
  dbSchema,
76
70
  logger,
77
71
  });
72
+ // Resolve the rate-limiter once here so every core shares the same instance
73
+ // for the lifetime of this context (i.e. the duration of a single request).
74
+ // Priority: explicit rateLimiter arg > auto-construct from redisClient > none.
75
+ // null is a valid explicit value meaning "disable rate limiting entirely".
76
+ let rateLimiter = inRateLimiter;
77
+ if (rateLimiter === undefined && redisClient != null) {
78
+ rateLimiter = new IpRateLimiter_1.IpRateLimiter(redisClient, logger);
79
+ }
78
80
  const sharedContext = {
79
81
  spaceId,
80
82
  apiKey,
@@ -87,15 +89,12 @@ const createContextDefault = async (args) => {
87
89
  requestedLang,
88
90
  authorization,
89
91
  fingerprint,
90
- // accountId,
91
- // roleId,
92
- // userId,
93
- req,
94
- res,
95
- headers,
96
- cookies,
97
92
  authorizationToken,
98
93
  isExternalDb: !!inDb,
94
+ // Rate limiting — undefined values are omitted so context stays clean when
95
+ // neither is configured.
96
+ ...(rateLimiter !== undefined ? { rateLimiter } : {}),
97
+ ...(globalRateLimit !== undefined ? { globalRateLimit } : {}),
99
98
  };
100
99
  return await (0, exports.createApiContext)({
101
100
  cores,
@@ -111,10 +110,9 @@ const createContextDefault = async (args) => {
111
110
  }
112
111
  },
113
112
  getCoreContext: async (args) => {
114
- // TODO: const { req } = args;
115
- let extendCoreConext = {};
113
+ let extendCoreContext = {};
116
114
  if (check_types_1.default.function(getCoreContext)) {
117
- extendCoreConext = await getCoreContext(args);
115
+ extendCoreContext = await getCoreContext(args);
118
116
  }
119
117
  return {
120
118
  db,
@@ -126,19 +124,19 @@ const createContextDefault = async (args) => {
126
124
  interserviceApiKey,
127
125
  jwtSecret,
128
126
  verifyTokenArgs,
129
- ...(extendCoreConext || {}),
127
+ ...(extendCoreContext || {}),
130
128
  };
131
129
  },
132
130
  getGatewayContext: async (args) => {
133
- let extendGatewayConext = {};
131
+ let extendGatewayContext = {};
134
132
  if (check_types_1.default.function(getGatewayContext)) {
135
- extendGatewayConext = await getGatewayContext(args);
133
+ extendGatewayContext = await getGatewayContext(args);
136
134
  }
137
135
  return {
138
136
  db,
139
137
  isProduction,
140
138
  logger,
141
- ...(extendGatewayConext || {}),
139
+ ...(extendGatewayContext || {}),
142
140
  };
143
141
  },
144
142
  });
@@ -1,3 +1,35 @@
1
1
  import { OpResult } from '@sdflc/api-helpers';
2
+ /**
3
+ * Validates each item in an array using a checkit-style validator and
4
+ * accumulates all field errors into a single OpResult.
5
+ *
6
+ * Returns the OpResult immediately with a top-level error if `arr` is not
7
+ * an array. Otherwise runs `validator.validateSync(item)` on each element
8
+ * and collects any field-level errors, prefixed with the item's index.
9
+ *
10
+ * Error key format: `[prefix][idx].fieldName`
11
+ * e.g. for prefix "items" and index 2: "items[2].email"
12
+ *
13
+ * Supports both single-message errors (`{ message }`) and multi-rule
14
+ * failures (`{ errors: [{ message }, ...] }`) from the checkit library,
15
+ * consistent with the handling in BaseCore.validationFailure().
16
+ *
17
+ * @param arr The array to validate
18
+ * @param validator A checkit-style validator with a `validateSync` method
19
+ * @param prefix Optional key prefix for error paths (e.g. "items", "params")
20
+ */
2
21
  export declare const checkArray: (arr: any, validator: any, prefix?: string) => OpResult;
22
+ /**
23
+ * Converts a checkit validation error object into a VALIDATION_FAILED OpResult.
24
+ *
25
+ * Iterates `checkItResult.errors` and adds each field's error message(s)
26
+ * to the result. Supports both single-message errors (`{ message }`) and
27
+ * multi-rule failures (`{ errors: [{ message }, ...] }`) from the checkit
28
+ * library, consistent with BaseCore.validationFailure().
29
+ *
30
+ * Returns an empty VALIDATION_FAILED result if `checkItResult` is null,
31
+ * undefined, or has no errors, rather than throwing.
32
+ *
33
+ * @param checkItResult A checkit validation error object
34
+ */
3
35
  export declare const createErrorOnCheckError: (checkItResult: any) => OpResult;
@@ -1,27 +1,93 @@
1
1
  "use strict";
2
+ // ./src/checkItHelpers.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.createErrorOnCheckError = exports.checkArray = void 0;
4
5
  const api_helpers_1 = require("@sdflc/api-helpers");
6
+ /**
7
+ * Validates each item in an array using a checkit-style validator and
8
+ * accumulates all field errors into a single OpResult.
9
+ *
10
+ * Returns the OpResult immediately with a top-level error if `arr` is not
11
+ * an array. Otherwise runs `validator.validateSync(item)` on each element
12
+ * and collects any field-level errors, prefixed with the item's index.
13
+ *
14
+ * Error key format: `[prefix][idx].fieldName`
15
+ * e.g. for prefix "items" and index 2: "items[2].email"
16
+ *
17
+ * Supports both single-message errors (`{ message }`) and multi-rule
18
+ * failures (`{ errors: [{ message }, ...] }`) from the checkit library,
19
+ * consistent with the handling in BaseCore.validationFailure().
20
+ *
21
+ * @param arr The array to validate
22
+ * @param validator A checkit-style validator with a `validateSync` method
23
+ * @param prefix Optional key prefix for error paths (e.g. "items", "params")
24
+ */
5
25
  const checkArray = (arr, validator, prefix) => {
6
26
  const result = new api_helpers_1.OpResult();
7
27
  if (!Array.isArray(arr)) {
8
- return result.addError(prefix || '', 'The value should be an array');
28
+ result.addError(prefix || '', 'The value should be an array');
29
+ return result;
9
30
  }
10
31
  arr.forEach((item, idx) => {
11
- const [itemResult] = validator.validateSync(item);
12
- if (itemResult) {
13
- Object.keys(itemResult.errors).forEach((key) => {
14
- result.addError(`${prefix || ''}[${idx}].${key}`, itemResult.errors[key].message);
15
- });
32
+ try {
33
+ const [itemResult] = validator.validateSync(item);
34
+ if (itemResult?.errors) {
35
+ Object.keys(itemResult.errors).forEach((key) => {
36
+ const fieldError = itemResult.errors[key];
37
+ const keyPath = `${prefix || ''}[${idx}].${key}`;
38
+ // Support both multi-rule failures ({ errors: [...] }) and
39
+ // single-message errors ({ message }) from the checkit library,
40
+ // consistent with BaseCore.validationFailure()
41
+ if (Array.isArray(fieldError.errors)) {
42
+ fieldError.errors.forEach((err) => {
43
+ result.addError(keyPath, err.message);
44
+ });
45
+ }
46
+ else {
47
+ result.addError(keyPath, fieldError.message);
48
+ }
49
+ });
50
+ }
51
+ }
52
+ catch (ex) {
53
+ // If the validator itself throws, add a descriptive error for that
54
+ // index rather than crashing the whole validation pass
55
+ result.addError(`${prefix || ''}[${idx}]`, `Validation failed unexpectedly: ${ex?.message ?? String(ex)}`);
16
56
  }
17
57
  });
18
58
  return result;
19
59
  };
20
60
  exports.checkArray = checkArray;
61
+ /**
62
+ * Converts a checkit validation error object into a VALIDATION_FAILED OpResult.
63
+ *
64
+ * Iterates `checkItResult.errors` and adds each field's error message(s)
65
+ * to the result. Supports both single-message errors (`{ message }`) and
66
+ * multi-rule failures (`{ errors: [{ message }, ...] }`) from the checkit
67
+ * library, consistent with BaseCore.validationFailure().
68
+ *
69
+ * Returns an empty VALIDATION_FAILED result if `checkItResult` is null,
70
+ * undefined, or has no errors, rather than throwing.
71
+ *
72
+ * @param checkItResult A checkit validation error object
73
+ */
21
74
  const createErrorOnCheckError = (checkItResult) => {
22
75
  const result = new api_helpers_1.OpResult({ code: api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED });
76
+ if (!checkItResult?.errors) {
77
+ return result;
78
+ }
23
79
  Object.keys(checkItResult.errors).forEach((key) => {
24
- result.addError(key, checkItResult.errors[key].message);
80
+ const fieldError = checkItResult.errors[key];
81
+ // Support both multi-rule failures ({ errors: [...] }) and
82
+ // single-message errors ({ message }) from the checkit library
83
+ if (Array.isArray(fieldError.errors)) {
84
+ fieldError.errors.forEach((err) => {
85
+ result.addError(key, err.message);
86
+ });
87
+ }
88
+ else {
89
+ result.addError(key, fieldError.message);
90
+ }
25
91
  });
26
92
  return result;
27
93
  };
@@ -1,18 +1,109 @@
1
1
  import { OpResult } from '@sdflc/api-helpers';
2
2
  import { BaseCoreActionsInterface, CommonValidatorArgs } from './interfaces';
3
- export declare const shouldHaveParams: (args: any) => boolean[] | OpResult[];
4
- export declare const shouldHaveId: (id: any) => boolean[] | OpResult[];
5
- export declare const validateSingleIntId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
6
- export declare const validateSingleUuidId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
7
- export declare const validateSingleTextId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
8
- export declare const validateMultipleIntIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
9
- export declare const validateMultipleUuidIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
10
- export declare const validateMultipleTextIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
11
- export declare const validateList: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
12
- export declare const validateGet: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
13
- export declare const validateRemove: (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
14
- export declare const validateGetMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
15
- export declare const validateRemoveMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
16
- export declare const validateCreate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
17
- export declare const validateUpdate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
18
- export declare const validateSet: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
3
+ /**
4
+ * Guards that `args` is a non-empty plain object.
5
+ * Returns `[result]` where result is a failed OpResult if the check fails,
6
+ * or `[true]` if it passes.
7
+ *
8
+ * Fix: added explicit object type check before Object.keys() to correctly
9
+ * reject non-objects (null, numbers, strings) rather than treating them
10
+ * as empty objects.
11
+ */
12
+ export declare const shouldHaveParams: (args: any) => [OpResult | true];
13
+ /**
14
+ * Guards that `id` is a non-null, non-empty value.
15
+ * Returns `[result]` where result is a failed OpResult if the check fails,
16
+ * or `[true]` if it passes.
17
+ *
18
+ * Fix: replaced falsy check `!id` with explicit null/empty-string check
19
+ * so that `id = 0` (a valid integer id) is not incorrectly rejected.
20
+ */
21
+ export declare const shouldHaveId: (id: any) => [OpResult | true];
22
+ /**
23
+ * Validates that `args.id` is a present integer.
24
+ */
25
+ export declare const validateSingleIntId: (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
26
+ /**
27
+ * Validates that `args.id` is a present UUID v4.
28
+ */
29
+ export declare const validateSingleUuidId: (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
30
+ /**
31
+ * Validates that `args.id` is a present non-empty string.
32
+ */
33
+ export declare const validateSingleTextId: (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
34
+ /**
35
+ * Validates that `args.ids` is a present array of integers.
36
+ */
37
+ export declare const validateMultipleIntIds: (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
38
+ /**
39
+ * Validates that `args.ids` is a present array of UUID v4 values.
40
+ */
41
+ export declare const validateMultipleUuidIds: (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
42
+ /**
43
+ * Validates that `args.ids` is a present array of non-empty strings.
44
+ */
45
+ export declare const validateMultipleTextIds: (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
46
+ /**
47
+ * Validates list filter args using caller-provided rules.
48
+ * Validates `args.filter` rather than `args` directly.
49
+ *
50
+ * Returns a factory function — call with `{ rules }` to get the validator:
51
+ * `validate: validateList({ rules: myCheckitRules })`
52
+ */
53
+ export declare const validateList: ({ rules }: CommonValidatorArgs) => (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
54
+ /**
55
+ * Validates `args` for a get() call using the core's configured idType.
56
+ * Selects the appropriate single-id rule set (int, UUID, or text).
57
+ * Returns `[true, {}]` immediately if idType is ID_TYPES.UNKNOWN or not set,
58
+ * allowing untyped cores to skip id validation.
59
+ */
60
+ export declare const validateGet: (args: any, opt: BaseCoreActionsInterface) => Promise<any[]>;
61
+ /**
62
+ * Validates `args.where` for a remove() call using the core's configured idType.
63
+ * First checks that `where` is a non-empty object via `shouldHaveParams`,
64
+ * then applies the appropriate single-id rule set.
65
+ * Returns `[true, {}]` if idType is ID_TYPES.UNKNOWN or not set.
66
+ */
67
+ export declare const validateRemove: (args: any, opt: BaseCoreActionsInterface) => Promise<any[]>;
68
+ /**
69
+ * Validates `args` for a getMany() call using the core's configured idType.
70
+ * Selects the appropriate multi-id rule set (int, UUID, or text).
71
+ * Returns `[true, {}]` immediately if idType is ID_TYPES.UNKNOWN or not set.
72
+ */
73
+ export declare const validateGetMany: (args: any, opt: BaseCoreActionsInterface) => Promise<any[]>;
74
+ /**
75
+ * Validates `args.where` for a removeMany() call using the core's configured idType.
76
+ *
77
+ * Fix: removeMany() passes `args = { where: [...] }` to its validator, so we
78
+ * must validate `args.where` rather than `args` directly.
79
+ * Previously this was an alias of validateGetMany which validated `args.ids`
80
+ * directly — that worked only when idType was UNKNOWN (rules were skipped),
81
+ * but would fail silently for typed cores since `args.ids` would be undefined.
82
+ */
83
+ export declare const validateRemoveMany: (args: any, opt: BaseCoreActionsInterface) => Promise<any[]>;
84
+ /**
85
+ * Validates `args.params` for a create() call using caller-provided rules.
86
+ * First checks that `params` is a non-empty object, then applies the rules.
87
+ *
88
+ * Returns a factory function — call with `{ rules }` to get the validator:
89
+ * `validate: validateCreate({ rules: myCheckitRules })`
90
+ */
91
+ export declare const validateCreate: ({ rules }: CommonValidatorArgs) => (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
92
+ /**
93
+ * Validates `args.where` and `args.params` for an update() call using
94
+ * caller-provided rules.
95
+ * Checks that both `where` and `params` are non-empty objects, then
96
+ * applies the rules to `params`.
97
+ *
98
+ * Returns a factory function — call with `{ rules }` to get the validator:
99
+ * `validate: validateUpdate({ rules: myCheckitRules })`
100
+ */
101
+ export declare const validateUpdate: ({ rules }: CommonValidatorArgs) => (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;
102
+ /**
103
+ * Validates `args.params` for a set() (upsert) call using caller-provided rules.
104
+ * Checks that `params` is a non-empty object, then applies the rules.
105
+ *
106
+ * Returns a factory function — call with `{ rules }` to get the validator:
107
+ * `validate: validateSet({ rules: myCheckitRules })`
108
+ */
109
+ export declare const validateSet: ({ rules }: CommonValidatorArgs) => (args: any, _opt: BaseCoreActionsInterface) => Promise<any[]>;