@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,4 +1,5 @@
1
1
  "use strict";
2
+ // ./src/userToken.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
@@ -7,63 +8,126 @@ exports.verifyUserToken = exports.createUserToken = exports.getDefaultJwtIssuer
7
8
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
9
  const uuid_1 = require("uuid");
9
10
  const api_helpers_1 = require("@sdflc/api-helpers");
10
- const constants_1 = require("./constants");
11
11
  const dayjs_1 = __importDefault(require("dayjs"));
12
+ const constants_1 = require("./constants");
13
+ /**
14
+ * Module-level defaults for JWT algorithm and issuer.
15
+ *
16
+ * These can be overridden at application startup via `setDefaultJwtAlgorithm()`
17
+ * and `setDefaultJwtIssuer()`. Note that these are module-level singletons —
18
+ * changing them affects all subsequent token operations in the process.
19
+ * In test environments, restore defaults between test suites if overriding.
20
+ */
12
21
  let defaultJwtAlgorithm = constants_1.DEFAULT_JWT_ALGORITHM;
13
22
  let defaultIssuer = constants_1.DEFAULT_JWT_ISSUER;
23
+ /**
24
+ * Overrides the default JWT signing algorithm for all subsequent operations.
25
+ * Defaults to HS256 (from DEFAULT_JWT_ALGORITHM).
26
+ */
14
27
  const setDefaultJwtAlgorithm = (algorithm) => {
15
28
  defaultJwtAlgorithm = algorithm;
16
29
  };
17
30
  exports.setDefaultJwtAlgorithm = setDefaultJwtAlgorithm;
31
+ /**
32
+ * Returns the current default JWT signing algorithm.
33
+ */
18
34
  const getDefaultJwtAlgorithm = () => {
19
35
  return defaultJwtAlgorithm;
20
36
  };
21
37
  exports.getDefaultJwtAlgorithm = getDefaultJwtAlgorithm;
38
+ /**
39
+ * Overrides the default JWT issuer claim for all subsequent operations.
40
+ * Defaults to DEFAULT_JWT_ISSUER.
41
+ */
22
42
  const setDefaultJwtIssuer = (issuer) => {
23
43
  defaultIssuer = issuer;
24
44
  };
25
45
  exports.setDefaultJwtIssuer = setDefaultJwtIssuer;
46
+ /**
47
+ * Returns the current default JWT issuer.
48
+ */
26
49
  const getDefaultJwtIssuer = () => {
27
50
  return defaultIssuer;
28
51
  };
29
52
  exports.getDefaultJwtIssuer = getDefaultJwtIssuer;
53
+ /**
54
+ * Helper to convert an array to a non-empty tuple type required by jsonwebtoken.
55
+ * Returns undefined for empty or absent arrays.
56
+ */
57
+ function toNonEmptyArray(arr) {
58
+ if (!arr || arr.length === 0)
59
+ return undefined;
60
+ return arr;
61
+ }
62
+ /**
63
+ * Signs a JWT token with the provided params and secret.
64
+ *
65
+ * When `useFingerprint` is true, a UUID fingerprint is generated and embedded
66
+ * in the token payload. The fingerprint should be stored in a secure httpOnly
67
+ * cookie and passed to `verifyUserToken()` to mitigate token theft.
68
+ *
69
+ * Returns an OpResult containing `{ token, fingerprint }` on success.
70
+ * `fingerprint` is null when `useFingerprint` is false.
71
+ *
72
+ * Note: `params.userId` is used as the JWT `subject` claim.
73
+ *
74
+ * @param params Token payload (userId, accountId, roleId, spaceId, lang, etc.)
75
+ * @param secret JWT signing secret
76
+ * @param opt Signing options (algorithm, audience, issuer, expiresIn, etc.)
77
+ */
30
78
  const createUserToken = (params, secret, opt) => {
31
79
  const { algorithm, audience, issuer, jwtid, noTimestamp, header, keyid, expiresIn, useFingerprint } = opt || {};
32
80
  if (!params || !secret) {
33
81
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'Failed to create user JWT');
34
82
  }
35
83
  if (useFingerprint) {
36
- const fingerprint = (0, uuid_1.v4)();
37
- params['fingerprint'] = fingerprint;
84
+ params['fingerprint'] = (0, uuid_1.v4)();
38
85
  }
39
- const token = jsonwebtoken_1.default.sign(params, secret, {
40
- algorithm: algorithm || defaultJwtAlgorithm,
86
+ const signOptions = {
87
+ algorithm: (algorithm || defaultJwtAlgorithm),
41
88
  audience,
42
89
  issuer: issuer || defaultIssuer,
43
90
  jwtid: jwtid || (0, uuid_1.v4)(),
44
91
  subject: params.userId,
45
92
  noTimestamp: noTimestamp ?? false,
46
- header,
93
+ header: header,
47
94
  keyid,
48
- expiresIn: expiresIn && !isNaN(expiresIn) ? expiresIn : undefined,
49
- });
50
- return api_helpers_1.OpResult.ok({ token, fingerprint: params.fingerprint });
95
+ expiresIn: expiresIn,
96
+ };
97
+ const token = jsonwebtoken_1.default.sign(params, secret, signOptions);
98
+ return api_helpers_1.OpResult.ok({ token, fingerprint: params['fingerprint'] ?? null });
51
99
  };
52
100
  exports.createUserToken = createUserToken;
53
- function toNonEmptyArray(arr) {
54
- if (!arr || arr.length === 0)
55
- return undefined;
56
- return arr;
57
- }
101
+ /**
102
+ * Verifies a JWT token against the provided secret and options.
103
+ *
104
+ * Returns a successful OpResult containing the decoded token payload,
105
+ * or a failed OpResult with an appropriate code:
106
+ * - VALIDATION_FAILED — args not provided
107
+ * - EXPIRED — token has expired (TokenExpiredError)
108
+ * - INVALID_SIGNATURE — token is malformed or signature is invalid (JsonWebTokenError)
109
+ * - UNAUTHORIZED — fingerprint mismatch or other verification failure
110
+ *
111
+ * Fingerprint verification:
112
+ * If the token payload contains a `fingerprint` field and `args.fingerprint`
113
+ * is provided, they are compared. A mismatch returns UNAUTHORIZED — this
114
+ * mitigates token theft where the attacker does not have the fingerprint cookie.
115
+ *
116
+ * @param token The JWT string to verify
117
+ * @param secret The secret used to sign the token
118
+ * @param args Verification options (algorithms, audience, issuer, fingerprint, etc.)
119
+ */
58
120
  const verifyUserToken = (token, secret, args) => {
59
- const { algorithms, audience, issuer, ignoreExpiration, ignoreNotBefore, subject, clockTolerance, maxAge, clockTimestamp, nonce, fingerprint, } = args || {};
121
+ // Guard must come before destructuring — args || {} in the destructure
122
+ // would make !args always false since it coerces to an object first
60
123
  if (!args) {
61
124
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'Cannot verify user token as there are no parameters specified');
62
125
  }
126
+ const { algorithms, audience, issuer, ignoreExpiration, ignoreNotBefore, subject, clockTolerance, maxAge, clockTimestamp, nonce, fingerprint, } = args;
63
127
  try {
64
128
  const issuerToUse = issuer || defaultIssuer;
65
129
  const obj = jsonwebtoken_1.default.verify(token, secret, {
66
- algorithms: algorithms || [defaultJwtAlgorithm],
130
+ algorithms: (algorithms || [defaultJwtAlgorithm]),
67
131
  audience: typeof audience === 'string' ? audience : toNonEmptyArray(audience),
68
132
  issuer: typeof issuerToUse === 'string' ? issuerToUse : toNonEmptyArray(issuerToUse),
69
133
  ignoreExpiration,
@@ -74,17 +138,18 @@ const verifyUserToken = (token, secret, args) => {
74
138
  clockTimestamp,
75
139
  nonce,
76
140
  });
77
- if (obj?.fingerprint && obj.fingerprint != fingerprint) {
141
+ // Fingerprint check — mitigates token theft when fingerprint cookie is used
142
+ if (obj?.fingerprint && obj.fingerprint !== fingerprint) {
78
143
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED, null, 'User unauthenticated');
79
144
  }
80
145
  return api_helpers_1.OpResult.ok(obj);
81
146
  }
82
147
  catch (ex) {
83
148
  if (ex.name === 'TokenExpiredError') {
84
- return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `User authorization has expired at ${(0, dayjs_1.default)(ex.expiredAt).toDate()}`);
149
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `User authorization has expired at ${(0, dayjs_1.default)(ex.expiredAt).toISOString()}`);
85
150
  }
86
- else if (ex.name === 'JsonWebTokenError') {
87
- return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.EXPIRED, null, `JWT is invalid, reason: ${ex.message}`);
151
+ if (ex.name === 'JsonWebTokenError') {
152
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.INVALID_SIGNATURE, null, `JWT is invalid: ${ex.message}`);
88
153
  }
89
154
  return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.UNAUTHORIZED, null, 'User unauthenticated');
90
155
  }
package/build/utils.d.ts CHANGED
@@ -1,2 +1,22 @@
1
+ /**
2
+ * Returns `func` if it is a function, otherwise returns `defaultFunc`.
3
+ * Useful for ensuring a callback is always callable.
4
+ *
5
+ * @param func Value to check
6
+ * @param defaultFunc Fallback function if `func` is not a function
7
+ */
1
8
  export declare const setFunction: (func: any, defaultFunc: () => any) => any;
9
+ /**
10
+ * Builds an object containing only the keys from `defaultFuncs` where
11
+ * the corresponding value in `obj` is a function.
12
+ *
13
+ * Keys present in `defaultFuncs` but missing or non-function in `obj`
14
+ * are omitted from the result entirely — no fallback is applied.
15
+ * Keys present in `obj` but not in `defaultFuncs` are ignored.
16
+ *
17
+ * Use `setFunction()` for single-function fallback with a default.
18
+ *
19
+ * @param obj Source object to read functions from
20
+ * @param defaultFuncs Defines which keys to look for in `obj`
21
+ */
2
22
  export declare const setFunctions: (obj: any, defaultFuncs?: any) => any;
package/build/utils.js CHANGED
@@ -1,18 +1,40 @@
1
1
  "use strict";
2
+ // ./src/utils.ts
2
3
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
5
  };
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
7
  exports.setFunctions = exports.setFunction = void 0;
7
8
  const check_types_1 = __importDefault(require("check-types"));
9
+ /**
10
+ * Returns `func` if it is a function, otherwise returns `defaultFunc`.
11
+ * Useful for ensuring a callback is always callable.
12
+ *
13
+ * @param func Value to check
14
+ * @param defaultFunc Fallback function if `func` is not a function
15
+ */
8
16
  const setFunction = (func, defaultFunc) => {
9
17
  return check_types_1.default.function(func) ? func : defaultFunc;
10
18
  };
11
19
  exports.setFunction = setFunction;
20
+ /**
21
+ * Builds an object containing only the keys from `defaultFuncs` where
22
+ * the corresponding value in `obj` is a function.
23
+ *
24
+ * Keys present in `defaultFuncs` but missing or non-function in `obj`
25
+ * are omitted from the result entirely — no fallback is applied.
26
+ * Keys present in `obj` but not in `defaultFuncs` are ignored.
27
+ *
28
+ * Use `setFunction()` for single-function fallback with a default.
29
+ *
30
+ * @param obj Source object to read functions from
31
+ * @param defaultFuncs Defines which keys to look for in `obj`
32
+ */
12
33
  const setFunctions = (obj, defaultFuncs = {}) => {
13
34
  const keys = Object.keys(defaultFuncs || {});
14
35
  return keys.reduce((acc, key) => {
15
- if (check_types_1.default.function(obj[key])) {
36
+ // use optional chaining to guard against null/undefined obj
37
+ if (check_types_1.default.function(obj?.[key])) {
16
38
  acc[key] = obj[key];
17
39
  }
18
40
  return acc;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.111",
3
+ "version": "1.0.113",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {
@@ -31,6 +31,7 @@
31
31
  "author": "Sergey Demidenko",
32
32
  "license": "ISC",
33
33
  "devDependencies": {
34
+ "@eslint/js": "^10.0.1",
34
35
  "@types/bcrypt": "^6.0.0",
35
36
  "@types/bluebird": "^3.5.42",
36
37
  "@types/check-types": "^11.2.2",
@@ -38,41 +39,41 @@
38
39
  "@types/is-uuid": "^1.0.2",
39
40
  "@types/jest": "^30.0.0",
40
41
  "@types/jsonwebtoken": "^9.0.10",
41
- "@types/lodash": "^4.17.21",
42
- "@types/node": "^25.0.0",
42
+ "@types/lodash": "^4.17.24",
43
+ "@types/node": "^25.5.0",
43
44
  "@types/uuid": "^10.0.0",
44
- "@typescript-eslint/eslint-plugin": "^8.49.0",
45
- "@typescript-eslint/parser": "^8.49.0",
46
- "eslint": "^9.39.1",
45
+ "@typescript-eslint/eslint-plugin": "^8.57.2",
46
+ "@typescript-eslint/parser": "^8.57.2",
47
+ "eslint": "^10.1.0",
47
48
  "eslint-config-prettier": "^10.1.8",
48
- "eslint-plugin-jest": "^29.2.1",
49
- "eslint-plugin-prettier": "^5.5.4",
49
+ "eslint-plugin-jest": "^29.15.1",
50
+ "eslint-plugin-prettier": "^5.5.5",
50
51
  "husky": "^9.1.7",
51
- "jest": "^30.2.0",
52
- "prettier": "^3.7.4",
53
- "rimraf": "^6.1.2",
52
+ "jest": "^30.3.0",
53
+ "prettier": "^3.8.1",
54
+ "rimraf": "^6.1.3",
54
55
  "run-script-os": "^1.1.6",
55
56
  "ts-jest": "^29.4.6",
56
57
  "ts-node": "^10.9.2",
57
58
  "typescript": "^5.9.3"
58
59
  },
59
60
  "dependencies": {
60
- "@sdflc/api-helpers": "^1.1.13",
61
- "@sdflc/utils": "^1.0.24",
61
+ "@sdflc/api-helpers": "^1.1.15",
62
+ "@sdflc/utils": "^1.0.28",
62
63
  "bcrypt": "^6.0.0",
63
64
  "bluebird": "^3.7.2",
64
65
  "check-types": "^11.2.3",
65
66
  "checkit": "^0.7.0",
66
67
  "dataloader": "^2.2.3",
67
- "dayjs": "^1.11.19",
68
+ "dayjs": "^1.11.20",
68
69
  "dotenv-safe": "^9.1.0",
69
70
  "is-uuid": "^1.0.2",
70
71
  "json-stable-stringify": "^1.3.0",
71
72
  "jsonwebtoken": "^9.0.3",
72
- "knex": "^3.1.0",
73
- "lodash": "^4.17.21",
74
- "pg": "^8.16.3",
75
- "redis": "^5.10.0",
73
+ "knex": "^3.2.6",
74
+ "lodash": "^4.17.23",
75
+ "pg": "^8.20.0",
76
+ "redis": "^5.11.0",
76
77
  "uuid": "^13.0.0"
77
78
  }
78
79
  }
@@ -1,17 +0,0 @@
1
- import { Logger } from '@sdflc/utils';
2
- /**
3
- * Base class for REST API controllers.
4
- */
5
- declare class BaseController {
6
- protected onResponse: any;
7
- protected logger: Logger;
8
- constructor(props: any);
9
- init(props: any): void;
10
- /**
11
- * Executes an action method and returns result in consistent way.
12
- * @param method a function to be executed
13
- * @returns HTTP response
14
- */
15
- json(method: any): (req: any, res: any, next: any) => Promise<void>;
16
- }
17
- export { BaseController };
@@ -1,63 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.BaseController = void 0;
7
- const check_types_1 = __importDefault(require("check-types"));
8
- const api_helpers_1 = require("@sdflc/api-helpers");
9
- const utils_1 = require("@sdflc/utils");
10
- /**
11
- * Base class for REST API controllers.
12
- */
13
- class BaseController {
14
- onResponse;
15
- logger;
16
- constructor(props) {
17
- if (check_types_1.default.function(props?.onResponse)) {
18
- this.onResponse = props?.onResponse;
19
- }
20
- else {
21
- this.onResponse = () => {
22
- /* TODO */
23
- };
24
- }
25
- this.logger = props?.logger instanceof utils_1.Logger ? props.logger : new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
26
- }
27
- init(props) {
28
- // const { app } = props;
29
- // set express app routes here:
30
- // app.post(`${root}/event-webhook`, this.json(this.eventWebhook));
31
- }
32
- /**
33
- * Executes an action method and returns result in consistent way.
34
- * @param method a function to be executed
35
- * @returns HTTP response
36
- */
37
- json(method) {
38
- return async (req, res, next) => {
39
- try {
40
- const result = await method(req, res, next);
41
- if (result instanceof api_helpers_1.OpResult) {
42
- res.status(result.getHttpStatus()).json(result.toJS());
43
- }
44
- else if (result?.redirectUrl) {
45
- res.redirect(result?.redirectUrl);
46
- next();
47
- }
48
- else if (result) {
49
- res.status(200).json(result);
50
- }
51
- else {
52
- res.status(204).json(new api_helpers_1.OpResult());
53
- }
54
- await this.onResponse(req, res, next);
55
- }
56
- catch (ex) {
57
- this.logger.log(`An exception has occured when processing REST API request on the entry point '${req.method} ${req.originalUrl}' from ${req.ip}`);
58
- next(ex);
59
- }
60
- };
61
- }
62
- }
63
- exports.BaseController = BaseController;
@@ -1,2 +0,0 @@
1
- import { BuildConfigOptions } from './interfaces';
2
- export declare const buildConfig: (dirName: string, opt?: BuildConfigOptions) => any;
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildConfig = void 0;
4
- const lodash_1 = require("lodash");
5
- const path_1 = require("path");
6
- const dotenv_safe_1 = require("dotenv-safe");
7
- const buildConfig = (dirName, opt) => {
8
- const opt2use = opt || {};
9
- (0, dotenv_safe_1.config)({
10
- path: (0, path_1.resolve)(dirName, opt2use.envFile || '.env'),
11
- allowEmptyValues: opt2use.allowEmptyValues != null ? opt2use.allowEmptyValues : true,
12
- example: (0, path_1.join)(dirName, opt2use.envFileExample || '.env.example'),
13
- });
14
- const env = Object.assign({ NODE_ENV: opt2use.defaultNodeEnv || 'development' }, process.env);
15
- /**
16
- * Creates an application settings consisting of environment variables
17
- */
18
- const envVars = Object.keys(env).reduce((acc, key) => {
19
- let value = env[key];
20
- const tryValue = (value || '').toLowerCase();
21
- if (tryValue === 'false') {
22
- value = false;
23
- }
24
- else if (tryValue === 'true') {
25
- value = true;
26
- }
27
- acc[(0, lodash_1.camelCase)(key)] = value;
28
- return acc;
29
- }, {});
30
- return {
31
- ...envVars,
32
- nodeEnv: env.NODE_ENV,
33
- isProduction: env.NODE_ENV === 'production',
34
- };
35
- };
36
- exports.buildConfig = buildConfig;
@@ -1,17 +0,0 @@
1
- import { Logger } from '@sdflc/utils';
2
- /**
3
- * Base class for REST API controllers.
4
- */
5
- declare class BaseController {
6
- protected onResponse: any;
7
- protected logger: Logger;
8
- constructor(props: any);
9
- init(props: any): void;
10
- /**
11
- * Executes an action method and returns result in consistent way.
12
- * @param method a function to be executed
13
- * @returns HTTP response
14
- */
15
- json(method: any): (req: any, res: any, next: any) => Promise<void>;
16
- }
17
- export { BaseController };
@@ -1,57 +0,0 @@
1
- import check from 'check-types';
2
- import { OpResult } from '@sdflc/api-helpers';
3
- import { Logger, LoggerLevels } from '@sdflc/utils';
4
- /**
5
- * Base class for REST API controllers.
6
- */
7
- class BaseController {
8
- onResponse;
9
- logger;
10
- constructor(props) {
11
- if (check.function(props?.onResponse)) {
12
- this.onResponse = props?.onResponse;
13
- }
14
- else {
15
- this.onResponse = () => {
16
- /* TODO */
17
- };
18
- }
19
- this.logger = props?.logger instanceof Logger ? props.logger : new Logger({ level: LoggerLevels.ERROR });
20
- }
21
- init(props) {
22
- // const { app } = props;
23
- // set express app routes here:
24
- // app.post(`${root}/event-webhook`, this.json(this.eventWebhook));
25
- }
26
- /**
27
- * Executes an action method and returns result in consistent way.
28
- * @param method a function to be executed
29
- * @returns HTTP response
30
- */
31
- json(method) {
32
- return async (req, res, next) => {
33
- try {
34
- const result = await method(req, res, next);
35
- if (result instanceof OpResult) {
36
- res.status(result.getHttpStatus()).json(result.toJS());
37
- }
38
- else if (result?.redirectUrl) {
39
- res.redirect(result?.redirectUrl);
40
- next();
41
- }
42
- else if (result) {
43
- res.status(200).json(result);
44
- }
45
- else {
46
- res.status(204).json(new OpResult());
47
- }
48
- await this.onResponse(req, res, next);
49
- }
50
- catch (ex) {
51
- this.logger.log(`An exception has occured when processing REST API request on the entry point '${req.method} ${req.originalUrl}' from ${req.ip}`);
52
- next(ex);
53
- }
54
- };
55
- }
56
- }
57
- export { BaseController };
@@ -1,2 +0,0 @@
1
- import { BuildConfigOptions } from './interfaces';
2
- export declare const buildConfig: (dirName: string, opt?: BuildConfigOptions) => any;
@@ -1,32 +0,0 @@
1
- import { camelCase } from 'lodash';
2
- import { join, resolve } from 'path';
3
- import { config } from 'dotenv-safe';
4
- export const buildConfig = (dirName, opt) => {
5
- const opt2use = opt || {};
6
- config({
7
- path: resolve(dirName, opt2use.envFile || '.env'),
8
- allowEmptyValues: opt2use.allowEmptyValues != null ? opt2use.allowEmptyValues : true,
9
- example: join(dirName, opt2use.envFileExample || '.env.example'),
10
- });
11
- const env = Object.assign({ NODE_ENV: opt2use.defaultNodeEnv || 'development' }, process.env);
12
- /**
13
- * Creates an application settings consisting of environment variables
14
- */
15
- const envVars = Object.keys(env).reduce((acc, key) => {
16
- let value = env[key];
17
- const tryValue = (value || '').toLowerCase();
18
- if (tryValue === 'false') {
19
- value = false;
20
- }
21
- else if (tryValue === 'true') {
22
- value = true;
23
- }
24
- acc[camelCase(key)] = value;
25
- return acc;
26
- }, {});
27
- return {
28
- ...envVars,
29
- nodeEnv: env.NODE_ENV,
30
- isProduction: env.NODE_ENV === 'production',
31
- };
32
- };