@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,13 +1,12 @@
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';
6
+ import { IpRateLimiter } from './IpRateLimiter';
5
7
  import { Database } from './Database';
6
8
  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
- */
9
+ import { resolveClientIp } from './resolveClientIp';
11
10
  export const createApiContext = async (args) => {
12
11
  const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
13
12
  const requestId = inRequestId || v4();
@@ -26,10 +25,7 @@ export const createApiContext = async (args) => {
26
25
  return acc;
27
26
  }, {});
28
27
  context.gateways = Object.keys(gateways || {}).reduce((acc, key) => {
29
- acc[camelCase(key)] = new gateways[key]({
30
- ...gatewayContext,
31
- context,
32
- });
28
+ acc[camelCase(key)] = new gateways[key]({ ...gatewayContext, context });
33
29
  return acc;
34
30
  }, {});
35
31
  if (check.function(extendContext)) {
@@ -37,12 +33,12 @@ export const createApiContext = async (args) => {
37
33
  }
38
34
  return context;
39
35
  };
40
- /**
41
- * Creates default a GraphQL context object with all avilable cores.
42
- * @returns {object} A context object with all available cores
43
- */
44
36
  export const createContextDefault = async (args) => {
45
- const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
37
+ const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb,
38
+ // Rate limiting — both optional. If redisClient is provided and no custom
39
+ // rateLimiter is given, a built-in IpRateLimiter is constructed here once
40
+ // and shared across every core for the lifetime of this context.
41
+ redisClient, rateLimiter: inRateLimiter, globalRateLimit, } = args || {};
46
42
  const headers = req.headers || { noHeadersSetup: true };
47
43
  const cookies = req.cookies || { noCookiesSetup: true };
48
44
  const authorization = (headers[HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
@@ -52,22 +48,28 @@ export const createContextDefault = async (args) => {
52
48
  const managementApiKey = headers[HEADERS.MANAGEMENT_API_KEY];
53
49
  const userAgent = headers[HEADERS.USER_AGENT];
54
50
  const referer = headers[HEADERS.REFERER];
55
- const ipAddress = headers[HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
51
+ // req.connection was removed in Node.js v19 — use req.socket instead
52
+ const ipAddress = resolveClientIp(headers, req);
56
53
  const acceptLanguage = headers[HEADERS.ACCEPT_LANGUAGE];
57
54
  const languages = extractLanguages(acceptLanguage);
58
55
  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
56
  const requestId = v4();
63
57
  const db = inDb
64
58
  ? inDb
65
59
  : new Database({
66
- dbType: dbType || knexConfig.client || '',
60
+ dbType: dbType || knexConfig?.client || '',
67
61
  knexConfig,
68
62
  dbSchema,
69
63
  logger,
70
64
  });
65
+ // Resolve the rate-limiter once here so every core shares the same instance
66
+ // for the lifetime of this context (i.e. the duration of a single request).
67
+ // Priority: explicit rateLimiter arg > auto-construct from redisClient > none.
68
+ // null is a valid explicit value meaning "disable rate limiting entirely".
69
+ let rateLimiter = inRateLimiter;
70
+ if (rateLimiter === undefined && redisClient != null) {
71
+ rateLimiter = new IpRateLimiter(redisClient, logger);
72
+ }
71
73
  const sharedContext = {
72
74
  spaceId,
73
75
  apiKey,
@@ -80,15 +82,12 @@ export const createContextDefault = async (args) => {
80
82
  requestedLang,
81
83
  authorization,
82
84
  fingerprint,
83
- // accountId,
84
- // roleId,
85
- // userId,
86
- req,
87
- res,
88
- headers,
89
- cookies,
90
85
  authorizationToken,
91
86
  isExternalDb: !!inDb,
87
+ // Rate limiting — undefined values are omitted so context stays clean when
88
+ // neither is configured.
89
+ ...(rateLimiter !== undefined ? { rateLimiter } : {}),
90
+ ...(globalRateLimit !== undefined ? { globalRateLimit } : {}),
92
91
  };
93
92
  return await createApiContext({
94
93
  cores,
@@ -104,10 +103,9 @@ export const createContextDefault = async (args) => {
104
103
  }
105
104
  },
106
105
  getCoreContext: async (args) => {
107
- // TODO: const { req } = args;
108
- let extendCoreConext = {};
106
+ let extendCoreContext = {};
109
107
  if (check.function(getCoreContext)) {
110
- extendCoreConext = await getCoreContext(args);
108
+ extendCoreContext = await getCoreContext(args);
111
109
  }
112
110
  return {
113
111
  db,
@@ -119,19 +117,19 @@ export const createContextDefault = async (args) => {
119
117
  interserviceApiKey,
120
118
  jwtSecret,
121
119
  verifyTokenArgs,
122
- ...(extendCoreConext || {}),
120
+ ...(extendCoreContext || {}),
123
121
  };
124
122
  },
125
123
  getGatewayContext: async (args) => {
126
- let extendGatewayConext = {};
124
+ let extendGatewayContext = {};
127
125
  if (check.function(getGatewayContext)) {
128
- extendGatewayConext = await getGatewayContext(args);
126
+ extendGatewayContext = await getGatewayContext(args);
129
127
  }
130
128
  return {
131
129
  db,
132
130
  isProduction,
133
131
  logger,
134
- ...(extendGatewayConext || {}),
132
+ ...(extendGatewayContext || {}),
135
133
  };
136
134
  },
137
135
  });
@@ -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,23 +1,89 @@
1
+ // ./src/checkItHelpers.ts
1
2
  import { OpResult, OP_RESULT_CODES } from '@sdflc/api-helpers';
3
+ /**
4
+ * Validates each item in an array using a checkit-style validator and
5
+ * accumulates all field errors into a single OpResult.
6
+ *
7
+ * Returns the OpResult immediately with a top-level error if `arr` is not
8
+ * an array. Otherwise runs `validator.validateSync(item)` on each element
9
+ * and collects any field-level errors, prefixed with the item's index.
10
+ *
11
+ * Error key format: `[prefix][idx].fieldName`
12
+ * e.g. for prefix "items" and index 2: "items[2].email"
13
+ *
14
+ * Supports both single-message errors (`{ message }`) and multi-rule
15
+ * failures (`{ errors: [{ message }, ...] }`) from the checkit library,
16
+ * consistent with the handling in BaseCore.validationFailure().
17
+ *
18
+ * @param arr The array to validate
19
+ * @param validator A checkit-style validator with a `validateSync` method
20
+ * @param prefix Optional key prefix for error paths (e.g. "items", "params")
21
+ */
2
22
  export const checkArray = (arr, validator, prefix) => {
3
23
  const result = new OpResult();
4
24
  if (!Array.isArray(arr)) {
5
- return result.addError(prefix || '', 'The value should be an array');
25
+ result.addError(prefix || '', 'The value should be an array');
26
+ return result;
6
27
  }
7
28
  arr.forEach((item, idx) => {
8
- const [itemResult] = validator.validateSync(item);
9
- if (itemResult) {
10
- Object.keys(itemResult.errors).forEach((key) => {
11
- result.addError(`${prefix || ''}[${idx}].${key}`, itemResult.errors[key].message);
12
- });
29
+ try {
30
+ const [itemResult] = validator.validateSync(item);
31
+ if (itemResult?.errors) {
32
+ Object.keys(itemResult.errors).forEach((key) => {
33
+ const fieldError = itemResult.errors[key];
34
+ const keyPath = `${prefix || ''}[${idx}].${key}`;
35
+ // Support both multi-rule failures ({ errors: [...] }) and
36
+ // single-message errors ({ message }) from the checkit library,
37
+ // consistent with BaseCore.validationFailure()
38
+ if (Array.isArray(fieldError.errors)) {
39
+ fieldError.errors.forEach((err) => {
40
+ result.addError(keyPath, err.message);
41
+ });
42
+ }
43
+ else {
44
+ result.addError(keyPath, fieldError.message);
45
+ }
46
+ });
47
+ }
48
+ }
49
+ catch (ex) {
50
+ // If the validator itself throws, add a descriptive error for that
51
+ // index rather than crashing the whole validation pass
52
+ result.addError(`${prefix || ''}[${idx}]`, `Validation failed unexpectedly: ${ex?.message ?? String(ex)}`);
13
53
  }
14
54
  });
15
55
  return result;
16
56
  };
57
+ /**
58
+ * Converts a checkit validation error object into a VALIDATION_FAILED OpResult.
59
+ *
60
+ * Iterates `checkItResult.errors` and adds each field's error message(s)
61
+ * to the result. Supports both single-message errors (`{ message }`) and
62
+ * multi-rule failures (`{ errors: [{ message }, ...] }`) from the checkit
63
+ * library, consistent with BaseCore.validationFailure().
64
+ *
65
+ * Returns an empty VALIDATION_FAILED result if `checkItResult` is null,
66
+ * undefined, or has no errors, rather than throwing.
67
+ *
68
+ * @param checkItResult A checkit validation error object
69
+ */
17
70
  export const createErrorOnCheckError = (checkItResult) => {
18
71
  const result = new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
72
+ if (!checkItResult?.errors) {
73
+ return result;
74
+ }
19
75
  Object.keys(checkItResult.errors).forEach((key) => {
20
- result.addError(key, checkItResult.errors[key].message);
76
+ const fieldError = checkItResult.errors[key];
77
+ // Support both multi-rule failures ({ errors: [...] }) and
78
+ // single-message errors ({ message }) from the checkit library
79
+ if (Array.isArray(fieldError.errors)) {
80
+ fieldError.errors.forEach((err) => {
81
+ result.addError(key, err.message);
82
+ });
83
+ }
84
+ else {
85
+ result.addError(key, fieldError.message);
86
+ }
21
87
  });
22
88
  return result;
23
89
  };
@@ -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[]>;