@ikonintegration/ikapi 4.0.0-alpha8 → 5.0.0-alpha1

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 (234) hide show
  1. package/.eslintignore +3 -0
  2. package/.eslintrc.cjs +81 -0
  3. package/.github/workflows/npmpublish.yml +8 -19
  4. package/.github/workflows/prs.yml +12 -0
  5. package/dist/index.d.ts +16 -0
  6. package/dist/index.js +27 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/package-lock.json +11886 -0
  9. package/dist/package.json +81 -0
  10. package/dist/src/API/Request.d.ts +125 -0
  11. package/dist/src/API/Request.js +185 -0
  12. package/dist/src/API/Request.js.map +1 -0
  13. package/dist/src/API/Response.d.ts +188 -0
  14. package/dist/src/API/Response.js +270 -0
  15. package/dist/src/API/Response.js.map +1 -0
  16. package/dist/src/BaseEvent/DynamoTransaction.d.ts +20 -0
  17. package/dist/src/BaseEvent/DynamoTransaction.js +81 -0
  18. package/dist/src/BaseEvent/DynamoTransaction.js.map +1 -0
  19. package/dist/src/BaseEvent/EventProcessor.d.ts +58 -0
  20. package/dist/src/BaseEvent/EventProcessor.js +101 -0
  21. package/dist/src/BaseEvent/EventProcessor.js.map +1 -0
  22. package/dist/src/BaseEvent/Process.d.ts +50 -0
  23. package/dist/src/BaseEvent/Process.js +64 -0
  24. package/dist/src/BaseEvent/Process.js.map +1 -0
  25. package/dist/src/BaseEvent/StepTransaction.d.ts +23 -0
  26. package/dist/src/BaseEvent/StepTransaction.js +27 -0
  27. package/dist/src/BaseEvent/StepTransaction.js.map +1 -0
  28. package/dist/src/BaseEvent/Transaction.d.ts +149 -0
  29. package/dist/src/BaseEvent/Transaction.js +224 -0
  30. package/dist/src/BaseEvent/Transaction.js.map +1 -0
  31. package/dist/src/Cache/Redis.d.ts +29 -0
  32. package/dist/src/Cache/Redis.js +80 -0
  33. package/dist/src/Cache/Redis.js.map +1 -0
  34. package/dist/src/Cache/types.d.ts +31 -0
  35. package/dist/src/Cache/types.js +2 -0
  36. package/dist/src/Cache/types.js.map +1 -0
  37. package/dist/src/Config/Configuration.d.ts +123 -0
  38. package/dist/src/Config/Configuration.js +109 -0
  39. package/dist/src/Config/Configuration.js.map +1 -0
  40. package/dist/src/Config/EnvironmentVar.d.ts +74 -0
  41. package/dist/src/Config/EnvironmentVar.js +138 -0
  42. package/dist/src/Config/EnvironmentVar.js.map +1 -0
  43. package/dist/src/Crypto/Crypto.d.ts +45 -0
  44. package/dist/src/Crypto/Crypto.js +72 -0
  45. package/dist/src/Crypto/Crypto.js.map +1 -0
  46. package/dist/src/Database/Database.d.ts +21 -0
  47. package/dist/src/Database/Database.js +15 -0
  48. package/dist/src/Database/Database.js.map +1 -0
  49. package/dist/src/Database/DatabaseManager.d.ts +47 -0
  50. package/dist/src/Database/DatabaseManager.js +60 -0
  51. package/dist/src/Database/DatabaseManager.js.map +1 -0
  52. package/dist/src/Database/DatabaseTransaction.d.ts +101 -0
  53. package/dist/src/Database/DatabaseTransaction.js +126 -0
  54. package/dist/src/Database/DatabaseTransaction.js.map +1 -0
  55. package/dist/src/Database/index.d.ts +10 -0
  56. package/dist/src/Database/index.js +15 -0
  57. package/dist/src/Database/index.js.map +1 -0
  58. package/dist/src/Database/integrations/dynamo/DynamoDatabase.d.ts +35 -0
  59. package/dist/src/Database/integrations/dynamo/DynamoDatabase.js +59 -0
  60. package/dist/src/Database/integrations/dynamo/DynamoDatabase.js.map +1 -0
  61. package/dist/src/Database/integrations/kysely/KyselyDatabase.d.ts +66 -0
  62. package/dist/src/Database/integrations/kysely/KyselyDatabase.js +86 -0
  63. package/dist/src/Database/integrations/kysely/KyselyDatabase.js.map +1 -0
  64. package/dist/src/Database/integrations/kysely/KyselyTransaction.d.ts +70 -0
  65. package/dist/src/Database/integrations/kysely/KyselyTransaction.js +118 -0
  66. package/dist/src/Database/integrations/kysely/KyselyTransaction.js.map +1 -0
  67. package/dist/src/Database/integrations/pgsql/PostgresDatabase.d.ts +36 -0
  68. package/dist/src/Database/integrations/pgsql/PostgresDatabase.js +54 -0
  69. package/dist/src/Database/integrations/pgsql/PostgresDatabase.js.map +1 -0
  70. package/dist/src/Database/integrations/pgsql/PostgresTransaction.d.ts +63 -0
  71. package/dist/src/Database/integrations/pgsql/PostgresTransaction.js +61 -0
  72. package/dist/src/Database/integrations/pgsql/PostgresTransaction.js.map +1 -0
  73. package/dist/src/Database/types.d.ts +76 -0
  74. package/dist/src/Database/types.js +2 -0
  75. package/dist/src/Database/types.js.map +1 -0
  76. package/dist/src/Globals.d.ts +93 -0
  77. package/dist/src/Globals.js +99 -0
  78. package/dist/src/Globals.js.map +1 -0
  79. package/dist/src/Logger/Logger.d.ts +161 -0
  80. package/dist/src/Logger/Logger.js +297 -0
  81. package/dist/src/Logger/Logger.js.map +1 -0
  82. package/dist/src/Mailer/Mailer.d.ts +78 -0
  83. package/dist/src/Mailer/Mailer.js +182 -0
  84. package/dist/src/Mailer/Mailer.js.map +1 -0
  85. package/dist/src/Publisher/Publisher.d.ts +39 -0
  86. package/dist/src/Publisher/Publisher.js +77 -0
  87. package/dist/src/Publisher/Publisher.js.map +1 -0
  88. package/dist/src/Server/RouteResolver.d.ts +33 -0
  89. package/dist/src/Server/RouteResolver.js +100 -0
  90. package/dist/src/Server/RouteResolver.js.map +1 -0
  91. package/dist/src/Server/Router.d.ts +157 -0
  92. package/dist/src/Server/Router.js +32 -0
  93. package/dist/src/Server/Router.js.map +1 -0
  94. package/dist/src/Server/lib/ContainerServer.d.ts +42 -0
  95. package/dist/src/Server/lib/ContainerServer.js +66 -0
  96. package/dist/src/Server/lib/ContainerServer.js.map +1 -0
  97. package/dist/src/Server/lib/Server.d.ts +45 -0
  98. package/dist/src/Server/lib/Server.js +93 -0
  99. package/dist/src/Server/lib/Server.js.map +1 -0
  100. package/dist/src/Server/lib/container/GenericHandler.d.ts +9 -0
  101. package/dist/src/Server/lib/container/GenericHandler.js +82 -0
  102. package/dist/src/Server/lib/container/GenericHandler.js.map +1 -0
  103. package/dist/src/Server/lib/container/GenericHandlerEvent.d.ts +52 -0
  104. package/dist/src/Server/lib/container/GenericHandlerEvent.js +132 -0
  105. package/dist/src/Server/lib/container/GenericHandlerEvent.js.map +1 -0
  106. package/dist/src/Server/lib/container/HealthHandler.d.ts +9 -0
  107. package/dist/src/Server/lib/container/HealthHandler.js +19 -0
  108. package/dist/src/Server/lib/container/HealthHandler.js.map +1 -0
  109. package/dist/src/Server/lib/container/Proxy.d.ts +67 -0
  110. package/dist/src/Server/lib/container/Proxy.js +143 -0
  111. package/dist/src/Server/lib/container/Proxy.js.map +1 -0
  112. package/dist/src/Server/lib/container/Utils.d.ts +14 -0
  113. package/dist/src/Server/lib/container/Utils.js +37 -0
  114. package/dist/src/Server/lib/container/Utils.js.map +1 -0
  115. package/dist/src/Util/AsyncSingleton.d.ts +31 -0
  116. package/dist/src/Util/AsyncSingleton.js +83 -0
  117. package/dist/src/Util/AsyncSingleton.js.map +1 -0
  118. package/dist/src/Util/Utils.d.ts +61 -0
  119. package/dist/src/Util/Utils.js +147 -0
  120. package/dist/src/Util/Utils.js.map +1 -0
  121. package/dist/src/Validation/Validator.d.ts +17 -0
  122. package/dist/src/Validation/Validator.js +39 -0
  123. package/dist/src/Validation/Validator.js.map +1 -0
  124. package/index.ts +41 -0
  125. package/jest.config.ts +37 -0
  126. package/jest.smoke.config.ts +34 -0
  127. package/package.json +66 -22
  128. package/src/API/Request.ts +214 -0
  129. package/src/API/Response.ts +370 -0
  130. package/src/BaseEvent/DynamoTransaction.ts +125 -0
  131. package/src/BaseEvent/EventProcessor.ts +140 -0
  132. package/src/BaseEvent/Process.ts +78 -0
  133. package/src/BaseEvent/StepTransaction.ts +35 -0
  134. package/src/BaseEvent/Transaction.ts +323 -0
  135. package/src/Cache/Redis.ts +89 -0
  136. package/src/Cache/types.ts +33 -0
  137. package/src/Config/Configuration.ts +199 -0
  138. package/src/Config/EnvironmentVar.ts +147 -0
  139. package/src/Crypto/Crypto.ts +89 -0
  140. package/src/Database/Database.ts +22 -0
  141. package/src/Database/DatabaseManager.ts +67 -0
  142. package/src/Database/DatabaseTransaction.ts +170 -0
  143. package/src/Database/index.ts +27 -0
  144. package/src/Database/integrations/dynamo/DynamoDatabase.ts +58 -0
  145. package/src/Database/integrations/kysely/KyselyDatabase.ts +99 -0
  146. package/src/Database/integrations/kysely/KyselyTransaction.ts +172 -0
  147. package/src/Database/integrations/pgsql/PostgresDatabase.ts +56 -0
  148. package/src/Database/integrations/pgsql/PostgresTransaction.ts +87 -0
  149. package/src/Database/types.ts +85 -0
  150. package/src/Globals.ts +103 -0
  151. package/src/Logger/Logger.ts +360 -0
  152. package/src/Mailer/Mailer.ts +217 -0
  153. package/src/Publisher/Publisher.ts +96 -0
  154. package/src/Server/RouteResolver.ts +124 -0
  155. package/src/Server/Router.ts +200 -0
  156. package/src/Server/lib/ContainerServer.ts +65 -0
  157. package/src/Server/lib/Server.ts +109 -0
  158. package/src/Server/lib/container/GenericHandler.ts +76 -0
  159. package/src/Server/lib/container/GenericHandlerEvent.ts +154 -0
  160. package/src/Server/lib/container/HealthHandler.ts +11 -0
  161. package/src/Server/lib/container/Proxy.ts +172 -0
  162. package/src/Server/lib/container/Utils.ts +33 -0
  163. package/src/Util/AsyncSingleton.ts +86 -0
  164. package/src/Util/Utils.ts +131 -0
  165. package/src/Validation/Validator.ts +45 -0
  166. package/tests/API/Request.test.ts +273 -0
  167. package/tests/API/Response.test.ts +367 -0
  168. package/tests/BaseEvent/DynamoTransaction.test.ts +272 -0
  169. package/tests/BaseEvent/EventProcessor.test.ts +263 -0
  170. package/tests/BaseEvent/Process.test.ts +47 -0
  171. package/tests/BaseEvent/StepTransaction.test.ts +44 -0
  172. package/tests/BaseEvent/Transaction.test.ts +402 -0
  173. package/tests/Cache/Redis-client.test.ts +90 -0
  174. package/tests/Cache/Redis-cluster.test.ts +100 -0
  175. package/tests/Config/Config.test.ts +205 -0
  176. package/tests/Config/EnvironmentVar.test.ts +251 -0
  177. package/tests/Crypto/Crypto.test.ts +88 -0
  178. package/tests/Database/DatabaseManager.test.ts +79 -0
  179. package/tests/Database/integrations/dynamo/DynamoDatabase.test.ts +44 -0
  180. package/tests/Database/integrations/kysely/KyselyDatabase.test.ts +113 -0
  181. package/tests/Database/integrations/kysely/KyselyTransaction.test.ts +119 -0
  182. package/tests/Database/integrations/pg/PostgresDatabase.test.ts +76 -0
  183. package/tests/Database/integrations/pg/PostgresTransaction.test.ts +118 -0
  184. package/tests/Logger/Logger.test.ts +215 -0
  185. package/tests/Mailer/Mailer.test.ts +59 -0
  186. package/tests/Publisher/Publisher.test.ts +60 -0
  187. package/tests/Server/RouteResolver.test.ts +116 -0
  188. package/tests/Server/Router.test.ts +39 -0
  189. package/tests/Server/lib/ContainerServer.test.ts +531 -0
  190. package/tests/Server/lib/Server.test.ts +12 -0
  191. package/tests/Server/lib/container/GenericHandler.test.ts +131 -0
  192. package/tests/Server/lib/container/GenericHandlerEvent.test.ts +103 -0
  193. package/tests/Server/lib/container/HealthHandler.test.ts +30 -0
  194. package/tests/Server/lib/container/Proxy.test.ts +268 -0
  195. package/tests/Server/lib/container/Utils.test.ts +47 -0
  196. package/tests/Test.utils.ts +78 -0
  197. package/tests/Utils/Utils.test.ts +230 -0
  198. package/tests/Validation/Validator.test.ts +82 -0
  199. package/tsconfig.json +26 -0
  200. package/tsconfig.smoke.json +26 -0
  201. package/index.js +0 -88
  202. package/src/API/IKRequest.js +0 -52
  203. package/src/API/IKResponse.js +0 -119
  204. package/src/API/IKUtils.js +0 -51
  205. package/src/BaseEvent/IKProcess.js +0 -77
  206. package/src/BaseEvent/IKTransaction.js +0 -139
  207. package/src/Cache/Prototype/IKCache.js +0 -17
  208. package/src/Cache/Redis/IKRedis.js +0 -148
  209. package/src/Database/DDB/IKDB.js +0 -56
  210. package/src/Database/DDB/IKDBBaseExpression.js +0 -130
  211. package/src/Database/DDB/IKDBBaseQuery.js +0 -151
  212. package/src/Database/DDB/IKDBQueryBatchGet.js +0 -37
  213. package/src/Database/DDB/IKDBQueryBatchWrite.js +0 -64
  214. package/src/Database/DDB/IKDBQueryDelete.js +0 -34
  215. package/src/Database/DDB/IKDBQueryGet.js +0 -48
  216. package/src/Database/DDB/IKDBQueryPut.js +0 -87
  217. package/src/Database/DDB/IKDBQueryScan.js +0 -45
  218. package/src/Database/DDB/IKDBQueryTransactionalWrite.js +0 -69
  219. package/src/Database/DDB/IKDBQueryUpdate.js +0 -219
  220. package/src/Database/DDB/_IKDBQueryTransactionalRead.js +0 -46
  221. package/src/Database/PSQL/IKDB.js +0 -41
  222. package/src/Database/PSQL/IKDBBaseQuery.js +0 -26
  223. package/src/Database/Prototype/IKDB.js +0 -21
  224. package/src/Database/Prototype/IKDBBaseQuery.js +0 -14
  225. package/src/IKDynamoStream.js +0 -42
  226. package/src/IKEventProcessor.js +0 -42
  227. package/src/IKGlobals.js +0 -24
  228. package/src/IKRouter.js +0 -47
  229. package/src/IKStepTransaction.js +0 -14
  230. package/src/Logger/IKLogger.js +0 -136
  231. package/src/Mailer/IKMailer.js +0 -68
  232. package/src/Publisher/IKPublisher.js +0 -44
  233. package/src/Tracker/IKExecutionTracker.js +0 -79
  234. package/src/Validation/IKValidation.js +0 -77
@@ -0,0 +1,64 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import Logger from '../Logger/Logger.js';
11
+ import Publisher from '../Publisher/Publisher.js';
12
+ /**
13
+ * Represents a long-running process that executes a given function at a specified interval.
14
+ */
15
+ export default class Process {
16
+ /**
17
+ * Constructs a new instance of the LongRunningProcess class.
18
+ * @param {ProcessConfig} config - The configuration object for the process.
19
+ * @param {number} interval - The interval at which the process should run.
20
+ * @returns None
21
+ */
22
+ constructor(config, interval) {
23
+ this.interval = interval;
24
+ this.logger = new Logger(config.logger, 'long-running-process');
25
+ this.publisher = new Publisher(config.publisher);
26
+ }
27
+ /**
28
+ * Executes the provided execution function at a specified interval.
29
+ * @param {Function} executionFunc - The function to execute.
30
+ * @returns None
31
+ */
32
+ execute(executionFunc) {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ this.logger.debug('Starting main process code');
35
+ //Program loop
36
+ this.timeout = setInterval(() => __awaiter(this, void 0, void 0, function* () {
37
+ yield this.iexecute(executionFunc);
38
+ }), this.interval);
39
+ });
40
+ }
41
+ /**
42
+ * Executes the given execution function asynchronously and handles any exceptions that occur.
43
+ * @param {Function} executionFunc - The function to execute.
44
+ * @returns {boolean} - Returns true if the execution failed, false otherwise.
45
+ */
46
+ iexecute(executionFunc) {
47
+ return __awaiter(this, void 0, void 0, function* () {
48
+ let executionFailed = true; //failed til we say no!
49
+ // safe execution handler
50
+ try {
51
+ // Execute
52
+ yield executionFunc(this);
53
+ executionFailed = false;
54
+ }
55
+ catch (e) {
56
+ /* EXECUTION FAIL */
57
+ this.logger.error('Exception when executing main process code. Rolling back DB!');
58
+ this.logger.exception(e);
59
+ }
60
+ return executionFailed;
61
+ });
62
+ }
63
+ }
64
+ //# sourceMappingURL=Process.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Process.js","sourceRoot":"","sources":["../../../src/BaseEvent/Process.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,MAAM,MAAM,qBAAqB,CAAA;AACxC,OAAO,SAAS,MAAM,2BAA2B,CAAA;AAOjD;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,OAAO;IAqB1B;;;;;OAKG;IACH,YAAY,MAAqB,EAAE,QAAgB;QACjD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAA;QAC/D,IAAI,CAAC,SAAS,GAAG,IAAI,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IAClD,CAAC;IAED;;;;OAIG;IACU,OAAO,CAAC,aAAa;;YAChC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,4BAA4B,CAAC,CAAA;YAC/C,cAAc;YACd,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,GAAS,EAAE;gBACpC,MAAM,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAA;YACpC,CAAC,CAAA,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAA;QACnB,CAAC;KAAA;IAED;;;;OAIG;IACW,QAAQ,CAAC,aAAa;;YAClC,IAAI,eAAe,GAAG,IAAI,CAAA,CAAC,uBAAuB;YAClD,yBAAyB;YACzB,IAAI,CAAC;gBACH,UAAU;gBACV,MAAM,aAAa,CAAC,IAAI,CAAC,CAAA;gBACzB,eAAe,GAAG,KAAK,CAAA;YACzB,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,oBAAoB;gBACpB,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAA;gBACjF,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;YAC1B,CAAC;YACD,OAAO,eAAe,CAAA;QACxB,CAAC;KAAA;CACF"}
@@ -0,0 +1,23 @@
1
+ import type { Context } from 'aws-lambda';
2
+ import Transaction, { TransactionConfig } from './Transaction.js';
3
+ import Response, { ResponseErrorType } from '../API/Response.js';
4
+ /**
5
+ * Represents a step transaction that extends the Transaction class.
6
+ */
7
+ export default class StepTransaction extends Transaction {
8
+ /**
9
+ * Constructor for creating a new Transaction object.
10
+ * @param {any} event - The event object.
11
+ * @param {Context} context - The context object.
12
+ * @param {TransactionConfig} [config] - Optional configuration for the transaction.
13
+ * @returns None
14
+ */
15
+ constructor(event: any, context: Context, config?: TransactionConfig);
16
+ /**
17
+ * Generates an error response with the provided error message and error code.
18
+ * @param {string} error - The error message to include in the response.
19
+ * @param {string} code - The error code associated with the error.
20
+ * @returns {Response<ResponseErrorType>} - The error response object.
21
+ */
22
+ protected getErrorResponse(error: string, code: string): Response<ResponseErrorType>;
23
+ }
@@ -0,0 +1,27 @@
1
+ import Transaction from './Transaction.js';
2
+ import Response from '../API/Response.js';
3
+ /**
4
+ * Represents a step transaction that extends the Transaction class.
5
+ */
6
+ export default class StepTransaction extends Transaction {
7
+ /**
8
+ * Constructor for creating a new Transaction object.
9
+ * @param {any} event - The event object.
10
+ * @param {Context} context - The context object.
11
+ * @param {TransactionConfig} [config] - Optional configuration for the transaction.
12
+ * @returns None
13
+ */
14
+ constructor(event, context, config) {
15
+ super(event, context, Object.assign({ syncReturn: true, throwOnErrors: true }, (config || {})));
16
+ }
17
+ /**
18
+ * Generates an error response with the provided error message and error code.
19
+ * @param {string} error - The error message to include in the response.
20
+ * @param {string} code - The error code associated with the error.
21
+ * @returns {Response<ResponseErrorType>} - The error response object.
22
+ */
23
+ getErrorResponse(error, code) {
24
+ return Response.StepFunctionResponse({ err: error, errCode: code }, 400);
25
+ }
26
+ }
27
+ //# sourceMappingURL=StepTransaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StepTransaction.js","sourceRoot":"","sources":["../../../src/BaseEvent/StepTransaction.ts"],"names":[],"mappings":"AAEA,OAAO,WAAkC,MAAM,kBAAkB,CAAA;AACjE,OAAO,QAA+B,MAAM,oBAAoB,CAAA;AAEhE;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,eAAgB,SAAQ,WAAW;IACtD;;;;;;OAMG;IACH,YAAY,KAAU,EAAE,OAAgB,EAAE,MAA0B;QAClE,KAAK,CAAC,KAAK,EAAE,OAAO,kBAClB,UAAU,EAAE,IAAI,EAChB,aAAa,EAAE,IAAI,IAEhB,CAAC,MAAM,IAAI,EAAE,CAAC,EACjB,CAAA;IACJ,CAAC;IAED;;;;;OAKG;IACO,gBAAgB,CAAC,KAAa,EAAE,IAAY;QACpD,OAAO,QAAQ,CAAC,oBAAoB,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,GAAG,CAAC,CAAA;IAC1E,CAAC;CACF"}
@@ -0,0 +1,149 @@
1
+ import type { APIGatewayEvent, Context, DynamoDBStreamEvent, SQSEvent } from 'aws-lambda';
2
+ import Request from '../API/Request.js';
3
+ import Response, { ResponseErrorType } from '../API/Response.js';
4
+ import type { DatabaseImplType, DatabaseTransactionType, DatabaseType, DbConfig } from '../Database/types.js';
5
+ import Logger, { LoggerConfig } from '../Logger/Logger.js';
6
+ import Publisher, { PublisherConfig } from '../Publisher/Publisher.js';
7
+ /**
8
+ * Defines a type for executing a transaction and returning a promise with the response.
9
+ * @param {TransactionType} transaction - The transaction to execute.
10
+ * @returns A promise that resolves to the response of the transaction.
11
+ */
12
+ export type TransactionExecution<TransactionType, ResponseInnerType, MiscRespType = never> = (transaction: TransactionType) => Promise<Response<ResponseInnerType> | Response<ResponseErrorType> | MiscRespType>;
13
+ /**
14
+ * Represents the configuration options for a transaction.
15
+ * @typedef {Object} TransactionConfig
16
+ * @property {boolean} [throwOnErrors] - Whether to throw an error if there are any errors during the transaction.
17
+ * @property {boolean} [syncReturn] - Whether to return the result of the transaction synchronously.
18
+ * @property {boolean} [skipCleanTmp] - Whether to skip cleaning the temporary folder, in EventProcessor.
19
+ * @property {LoggerConfig} [logger] - The configuration options for the logger.
20
+ * @property {PublisherConfig} [publisher] - The configuration options for the publisher.
21
+ */
22
+ export type TransactionConfig = {
23
+ throwOnErrors?: boolean;
24
+ syncReturn?: boolean;
25
+ skipCleanTmp?: boolean;
26
+ logger?: LoggerConfig;
27
+ publisher?: PublisherConfig;
28
+ };
29
+ /**
30
+ * Represents a simple string dictionary with string values
31
+ */
32
+ export type StringMap = {
33
+ [key: string]: string | null;
34
+ };
35
+ /**
36
+ * Represents a transaction object that handles the execution of a request and manages the response.
37
+ * @template InputType - The type of the input data for the transaction.
38
+ * @template ResponseInnerType - The type of the inner response data for the transaction.
39
+ * @template MiscRespType - The type of miscellaneous response data for the transaction.
40
+ */
41
+ export default class Transaction<InputType = never, ResponseInnerType = null, MiscRespType = never, PathParamsType = StringMap, QueryParamsType = StringMap> {
42
+ /**
43
+ * The instance of the DatabaseManager class used for managing the database.
44
+ */
45
+ private databaseManager;
46
+ /**
47
+ * An array of database transactions.
48
+ * @type {DatabaseTransaction[]}
49
+ */
50
+ private transactions;
51
+ /**
52
+ * Represents an event object.
53
+ * @private
54
+ * @type {any}
55
+ */
56
+ private event;
57
+ /**
58
+ * The context object for the current instance.
59
+ */
60
+ private context;
61
+ /**
62
+ * The response object that can hold different types of responses.
63
+ * @type {Response<ResponseInnerType | ResponseErrorType> | MiscRespType | null}
64
+ */
65
+ private response;
66
+ /**
67
+ * A private boolean variable indicating whether the return value of a synchronous operation
68
+ * should be synchronized with the calling thread.
69
+ */
70
+ private syncReturn;
71
+ /**
72
+ * A boolean flag indicating whether retroactive errors are enabled or not.
73
+ * @private
74
+ */
75
+ private retrowErrors;
76
+ /**
77
+ * A logger object used for logging messages, errors, and other information.
78
+ * @readonly
79
+ */
80
+ readonly logger: Logger;
81
+ /**
82
+ * The request object for making a request of type InputType.
83
+ * @readonly
84
+ */
85
+ readonly request: Request<InputType, PathParamsType, QueryParamsType>;
86
+ /**
87
+ * The publisher of the content.
88
+ */
89
+ readonly publisher: Publisher;
90
+ /**
91
+ * A function that acts as a response proxy for a given response object.
92
+ * @param {Response<ResponseInnerType>} response - The response object to proxy.
93
+ * @returns A promise that resolves to void.
94
+ */
95
+ responseProxy: ((response: Response<ResponseInnerType>) => Promise<void>) | null;
96
+ /**
97
+ * Constructs a new instance of the Transaction class.
98
+ * @param {APIGatewayEvent | SQSEvent | DynamoDBStreamEvent} event - The event object passed to the Lambda function.
99
+ * @param {Context} context - The context object passed to the Lambda function.
100
+ * @param {TransactionConfig} [config] - Optional configuration object for the transaction.
101
+ * @returns None
102
+ */
103
+ constructor(event: APIGatewayEvent | SQSEvent | DynamoDBStreamEvent, context: Context, config?: TransactionConfig);
104
+ /**
105
+ * Executes a transaction using the provided execution function and returns a promise
106
+ * that resolves to the response or miscellaneous response.
107
+ * @param {TransactionExecution<Transaction<InputType, ResponseInnerType, MiscRespType>, ResponseInnerType, MiscRespType>} executionFunc - The execution function to be executed.
108
+ * @returns {Promise<Response<ResponseInnerType | ResponseErrorType> | MiscRespType>} - A promise that resolves to the response or miscellaneous response.
109
+ */
110
+ execute(executionFunc: TransactionExecution<Transaction<InputType, ResponseInnerType, MiscRespType, PathParamsType, QueryParamsType>, ResponseInnerType, MiscRespType>): Promise<Response<ResponseInnerType | ResponseErrorType> | MiscRespType | null>;
111
+ /**
112
+ * Executes a transaction using the provided execution function and handles the response.
113
+ * @param {TransactionExecution<Transaction<InputType, ResponseInnerType, MiscRespType>, ResponseInnerType, MiscRespType>} executionFunc - The function to execute the transaction.
114
+ * @returns {Promise<boolean>} - A promise that resolves to a boolean indicating whether the execution failed or not.
115
+ */
116
+ private iexecute;
117
+ /**
118
+ * Retrieves a database transaction based on the provided database configuration.
119
+ * @param {DbConfig<S>} config - The configuration object for the database.
120
+ * @returns {Promise<DatabaseTransactionType<S, DBSchema>>} A promise that resolves to the database transaction.
121
+ */
122
+ getDbTransaction<S extends DatabaseType, DBSchema>(config: DbConfig<S>): Promise<DatabaseTransactionType<S, DBSchema>>;
123
+ /**
124
+ * Retrieves a database instance based on the provided configuration.
125
+ * @param {DbConfig<S>} config - The configuration object specifying the type of database.
126
+ * @returns {DatabaseImplType<S, DBSchema>} A database instance based on the provided configuration.
127
+ */
128
+ getDatabase<S extends DatabaseType, DBSchema>(config: DbConfig<S>): DatabaseImplType<S, DBSchema>;
129
+ /**
130
+ * Get the remaining time in milliseconds for the current execution context.
131
+ * @returns {number} The remaining time in milliseconds, or -1 if the time is not available.
132
+ */
133
+ getRemainingTimeInMillis(): number;
134
+ private executeDBTransactions;
135
+ /**
136
+ * Executes a logger flush operation with error handling and logging.
137
+ * @param {Function} safeExecution - The function to execute safely.
138
+ * @returns None
139
+ * @throws {Error} - If `retrowErrors` is true and an error occurs during execution.
140
+ */
141
+ private executeLoggerFlush;
142
+ /**
143
+ * Generates an error response with the provided error message and code.
144
+ * @param {string} error - The error message to include in the response.
145
+ * @param {string} code - The error code associated with the response.
146
+ * @returns {Response<ResponseErrorType>} - The error response object.
147
+ */
148
+ protected getErrorResponse(error: string, code: string): Response<ResponseErrorType>;
149
+ }
@@ -0,0 +1,224 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import Request from '../API/Request.js';
11
+ import Response from '../API/Response.js';
12
+ import { DatabaseManager } from '../Database/DatabaseManager.js';
13
+ import Globals from '../Globals.js';
14
+ import Logger from '../Logger/Logger.js';
15
+ import Publisher from '../Publisher/Publisher.js';
16
+ /**
17
+ * Represents a transaction object that handles the execution of a request and manages the response.
18
+ * @template InputType - The type of the input data for the transaction.
19
+ * @template ResponseInnerType - The type of the inner response data for the transaction.
20
+ * @template MiscRespType - The type of miscellaneous response data for the transaction.
21
+ */
22
+ export default class Transaction {
23
+ /**
24
+ * Constructs a new instance of the Transaction class.
25
+ * @param {APIGatewayEvent | SQSEvent | DynamoDBStreamEvent} event - The event object passed to the Lambda function.
26
+ * @param {Context} context - The context object passed to the Lambda function.
27
+ * @param {TransactionConfig} [config] - Optional configuration object for the transaction.
28
+ * @returns None
29
+ */
30
+ constructor(event, context, config) {
31
+ /**
32
+ * The instance of the DatabaseManager class used for managing the database.
33
+ */
34
+ this.databaseManager = DatabaseManager.INSTANCE;
35
+ /**
36
+ * An array of database transactions.
37
+ * @type {DatabaseTransaction[]}
38
+ */
39
+ this.transactions = [];
40
+ const transactionId = context.awsRequestId
41
+ ? context.awsRequestId
42
+ : event.requestContext
43
+ ? event.requestContext.requestId
44
+ : 'unknown';
45
+ // transaction ctx
46
+ this.event = event;
47
+ this.context = context;
48
+ // when set, this will be called with the response context right before calling the context suceed/fail - useful for writing the resp for example.
49
+ this.responseProxy = null;
50
+ // transaction flags
51
+ this.syncReturn = !!(config === null || config === void 0 ? void 0 : config.syncReturn);
52
+ this.retrowErrors = !!(config === null || config === void 0 ? void 0 : config.throwOnErrors); /* retrow internal errors */
53
+ // components
54
+ this.logger = new Logger(config === null || config === void 0 ? void 0 : config.logger, transactionId);
55
+ this.request = new Request(this.event, this.context, this.logger);
56
+ this.publisher = new Publisher(config === null || config === void 0 ? void 0 : config.publisher);
57
+ }
58
+ /**
59
+ * Executes a transaction using the provided execution function and returns a promise
60
+ * that resolves to the response or miscellaneous response.
61
+ * @param {TransactionExecution<Transaction<InputType, ResponseInnerType, MiscRespType>, ResponseInnerType, MiscRespType>} executionFunc - The execution function to be executed.
62
+ * @returns {Promise<Response<ResponseInnerType | ResponseErrorType> | MiscRespType>} - A promise that resolves to the response or miscellaneous response.
63
+ */
64
+ execute(executionFunc) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ yield this.executeLoggerFlush(() => __awaiter(this, void 0, void 0, function* () {
67
+ yield this.executeDBTransactions(() => __awaiter(this, void 0, void 0, function* () {
68
+ return yield this.iexecute(executionFunc);
69
+ }));
70
+ }));
71
+ // return raw response if sync return is requested
72
+ if (this.syncReturn)
73
+ return this.response;
74
+ // allow request to async succeed through lambda context
75
+ return null;
76
+ });
77
+ }
78
+ /**
79
+ * Executes a transaction using the provided execution function and handles the response.
80
+ * @param {TransactionExecution<Transaction<InputType, ResponseInnerType, MiscRespType>, ResponseInnerType, MiscRespType>} executionFunc - The function to execute the transaction.
81
+ * @returns {Promise<boolean>} - A promise that resolves to a boolean indicating whether the execution failed or not.
82
+ */
83
+ iexecute(executionFunc) {
84
+ return __awaiter(this, void 0, void 0, function* () {
85
+ let executionFailed = true; //failed til we say no!
86
+ //safe execution handler
87
+ try {
88
+ //Execute
89
+ this.logger.debug('Starting main request code');
90
+ this.response = yield executionFunc(this);
91
+ //Answer client
92
+ if (this.response && this.response instanceof Response) {
93
+ yield this.response.build(this.context, this, this.syncReturn);
94
+ executionFailed = !!(this.response.getBody() && this.response.getBody()['rollback']);
95
+ }
96
+ else if (this.syncReturn && this.response) {
97
+ this.logger.log('Sync return with different response object');
98
+ this.logger.debug(this.response);
99
+ executionFailed = false;
100
+ }
101
+ else {
102
+ this.response = this.getErrorResponse(Globals.ErrorResponseInvalidServerResponse, Globals.ErrorCode_APIError);
103
+ yield this.response.build(this.context, this, this.syncReturn);
104
+ this.logger.error('Invalid response object from main request code.');
105
+ }
106
+ }
107
+ catch (e) {
108
+ /*EXECUTION FAIL*/
109
+ this.logger.error('Exception when executing main request code.');
110
+ this.logger.exception(e);
111
+ //retrow?
112
+ if (this.retrowErrors)
113
+ throw e;
114
+ //envelope exception?
115
+ this.response = this.getErrorResponse(Globals.ErrorResponseUnhandledError, Globals.ErrorCode_APIError);
116
+ yield this.response.build(this.context, this, this.syncReturn);
117
+ }
118
+ return executionFailed;
119
+ });
120
+ }
121
+ /**
122
+ * Retrieves a database transaction based on the provided database configuration.
123
+ * @param {DbConfig<S>} config - The configuration object for the database.
124
+ * @returns {Promise<DatabaseTransactionType<S, DBSchema>>} A promise that resolves to the database transaction.
125
+ */
126
+ getDbTransaction(config) {
127
+ return __awaiter(this, void 0, void 0, function* () {
128
+ const db = this.getDatabase(config);
129
+ const dbTrans = yield db.transaction();
130
+ this.transactions.push(dbTrans);
131
+ return dbTrans;
132
+ });
133
+ }
134
+ /**
135
+ * Retrieves a database instance based on the provided configuration.
136
+ * @param {DbConfig<S>} config - The configuration object specifying the type of database.
137
+ * @returns {DatabaseImplType<S, DBSchema>} A database instance based on the provided configuration.
138
+ */
139
+ getDatabase(config) {
140
+ return this.databaseManager.create(config);
141
+ }
142
+ /**
143
+ * Get the remaining time in milliseconds for the current execution context.
144
+ * @returns {number} The remaining time in milliseconds, or -1 if the time is not available.
145
+ */
146
+ getRemainingTimeInMillis() {
147
+ var _a, _b;
148
+ return ((_b = (_a = this.context) === null || _a === void 0 ? void 0 : _a.getRemainingTimeInMillis) === null || _b === void 0 ? void 0 : _b.call(_a)) || -1;
149
+ }
150
+ /*
151
+ * Executes a series of database transactions in a safe manner.
152
+ * @param {Function} safeExecution - The function that contains the database transactions to be executed.
153
+ * @returns None
154
+ * @throws {Error} - If an exception occurs during the execution of the transactions and `retrowErrors` is true.
155
+ */
156
+ executeDBTransactions(safeExecution) {
157
+ return __awaiter(this, void 0, void 0, function* () {
158
+ try {
159
+ // Execute
160
+ const execFailed = yield safeExecution();
161
+ for (const transaction of [...this.transactions].reverse()) {
162
+ try {
163
+ yield transaction[execFailed ? 'closeFailure' : 'closeSuccess']();
164
+ }
165
+ catch (e) {
166
+ this.logger.error('Exception when closing DB transactions after success.');
167
+ this.logger.exception(e);
168
+ }
169
+ }
170
+ }
171
+ catch (e) {
172
+ /* this part of the code handle exceptions at transaction level,
173
+ so probably a bug but we still handle such */
174
+ for (const transaction of [...this.transactions].reverse()) {
175
+ try {
176
+ yield transaction.closeFailure();
177
+ }
178
+ catch (e) {
179
+ this.logger.error('Exception when closing DB transactions after failure.');
180
+ this.logger.exception(e);
181
+ }
182
+ }
183
+ this.logger.error('Exception when executing DB transactions.');
184
+ this.logger.log(e.stack);
185
+ //retrow?
186
+ if (this.retrowErrors)
187
+ throw e;
188
+ }
189
+ });
190
+ }
191
+ /**
192
+ * Executes a logger flush operation with error handling and logging.
193
+ * @param {Function} safeExecution - The function to execute safely.
194
+ * @returns None
195
+ * @throws {Error} - If `retrowErrors` is true and an error occurs during execution.
196
+ */
197
+ executeLoggerFlush(safeExecution) {
198
+ return __awaiter(this, void 0, void 0, function* () {
199
+ try {
200
+ yield safeExecution();
201
+ }
202
+ catch (e) {
203
+ this.logger.error('Exception when flushing logs.');
204
+ this.logger.exception(e);
205
+ //retrow?
206
+ if (this.retrowErrors)
207
+ throw e;
208
+ }
209
+ finally {
210
+ this.logger.debug('Transaction ended');
211
+ }
212
+ });
213
+ }
214
+ /**
215
+ * Generates an error response with the provided error message and code.
216
+ * @param {string} error - The error message to include in the response.
217
+ * @param {string} code - The error code associated with the response.
218
+ * @returns {Response<ResponseErrorType>} - The error response object.
219
+ */
220
+ getErrorResponse(error, code) {
221
+ return Response.BadRequestResponseWithRollback(error, code);
222
+ }
223
+ }
224
+ //# sourceMappingURL=Transaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Transaction.js","sourceRoot":"","sources":["../../../src/BaseEvent/Transaction.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,OAAO,MAAM,mBAAmB,CAAA;AACvC,OAAO,QAA+B,MAAM,oBAAoB,CAAA;AAChE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAA;AAQhE,OAAO,OAAO,MAAM,eAAe,CAAA;AACnC,OAAO,MAAwB,MAAM,qBAAqB,CAAA;AAC1D,OAAO,SAA8B,MAAM,2BAA2B,CAAA;AAkCtE;;;;;GAKG;AACH,MAAM,CAAC,OAAO,OAAO,WAAW;IA8D9B;;;;;;OAMG;IACH,YACE,KAAuD,EACvD,OAAgB,EAChB,MAA0B;QAjE5B;;WAEG;QACK,oBAAe,GAAoB,eAAe,CAAC,QAAQ,CAAA;QACnE;;;WAGG;QACK,iBAAY,GAA0B,EAAE,CAAA;QA2D9C,MAAM,aAAa,GAAG,OAAO,CAAC,YAAY;YACxC,CAAC,CAAC,OAAO,CAAC,YAAY;YACtB,CAAC,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+B,CAAC,CAAA;gBAClD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;gBACxB,SAAS;gBACT,IAAI,IAAI,CAAC,YAAY;oBAAE,MAAM,CAAC,CAAA;YAChC,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAA;YACxC,CAAC;QACH,CAAC;KAAA;IAED;;;;;OAKG;IACO,gBAAgB,CAAC,KAAa,EAAE,IAAY;QACpD,OAAO,QAAQ,CAAC,8BAA8B,CAAC,KAAK,EAAE,IAAI,CAAC,CAAA;IAC7D,CAAC;CACF"}
@@ -0,0 +1,29 @@
1
+ import { RedisClientType, RedisClusterType } from 'redis';
2
+ import { CacheConfig } from './types.js';
3
+ /**
4
+ * Represents a Redis cache connection class.
5
+ */
6
+ export default class Redis {
7
+ private static singleton;
8
+ /**
9
+ * A private static property that holds a reference to the redis.createClient function.
10
+ * This property is used to create client.
11
+ */
12
+ private static ClientFactory;
13
+ /**
14
+ * A private static property that references the createCluster function.
15
+ * This property can be used to create clusters within the class.
16
+ */
17
+ private static ClusterFactory;
18
+ static connection(config: CacheConfig<'redis'>): Promise<RedisClientType | RedisClusterType>;
19
+ private static connectionFactory;
20
+ /**
21
+ * Establishes a connection to a Redis client based on the provided configuration
22
+ * and holds it for reusability. If connection is detected closed, new connection is
23
+ * initialized and established.
24
+ * @param {CacheConfig<'redis'>} config - The configuration object for connecting to the Redis client.
25
+ * @returns {Promise<RedisClientType>} A promise that resolves to the Redis client connection.
26
+ */
27
+ private static redisClientConnection;
28
+ private static redisClusterConnection;
29
+ }
@@ -0,0 +1,80 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var _a;
11
+ import { createCluster, createClient } from 'redis';
12
+ import AsyncSingleton from '../Util/AsyncSingleton.js';
13
+ /**
14
+ * Represents a Redis cache connection class.
15
+ */
16
+ class Redis {
17
+ static connection(config) {
18
+ return _a.singleton.instance(config);
19
+ }
20
+ static connectionFactory(config) {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ if (config.clusterMode)
23
+ return _a.redisClusterConnection(config);
24
+ else
25
+ return _a.redisClientConnection(config);
26
+ });
27
+ }
28
+ /**
29
+ * Establishes a connection to a Redis client based on the provided configuration
30
+ * and holds it for reusability. If connection is detected closed, new connection is
31
+ * initialized and established.
32
+ * @param {CacheConfig<'redis'>} config - The configuration object for connecting to the Redis client.
33
+ * @returns {Promise<RedisClientType>} A promise that resolves to the Redis client connection.
34
+ */
35
+ static redisClientConnection(config) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ console.debug('Starting remote client cache connection');
38
+ const connection = _a.ClientFactory(Object.assign(Object.assign({ username: config.username }, (config.password ? { password: config.password } : {})), { disableOfflineQueue: true, socket: {
39
+ host: config.hostname,
40
+ tls: config.enableTLS,
41
+ connectTimeout: 10000,
42
+ } }));
43
+ yield connection.connect();
44
+ return connection;
45
+ });
46
+ }
47
+ static redisClusterConnection(config) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ console.debug('Starting remote cluster cache connection');
50
+ const connection = _a.ClusterFactory({
51
+ defaults: Object.assign(Object.assign({ username: config.username }, (config.password ? { password: config.password } : {})), { socket: {
52
+ tls: config.enableTLS,
53
+ connectTimeout: 10000,
54
+ } }),
55
+ rootNodes: [
56
+ {
57
+ url: `redis://${config.username}:${config.username}@${config.hostname}:6379`,
58
+ disableOfflineQueue: true,
59
+ },
60
+ ],
61
+ });
62
+ yield connection.connect();
63
+ return connection;
64
+ });
65
+ }
66
+ }
67
+ _a = Redis;
68
+ Redis.singleton = new AsyncSingleton(_a.connectionFactory, (c) => __awaiter(void 0, void 0, void 0, function* () { return c.isOpen; }));
69
+ /**
70
+ * A private static property that holds a reference to the redis.createClient function.
71
+ * This property is used to create client.
72
+ */
73
+ Redis.ClientFactory = createClient;
74
+ /**
75
+ * A private static property that references the createCluster function.
76
+ * This property can be used to create clusters within the class.
77
+ */
78
+ Redis.ClusterFactory = createCluster;
79
+ export default Redis;
80
+ //# sourceMappingURL=Redis.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Redis.js","sourceRoot":"","sources":["../../../src/Cache/Redis.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAO,EAAqC,aAAa,EAAE,YAAY,EAAE,MAAM,OAAO,CAAA;AAGtF,OAAO,cAAc,MAAM,2BAA2B,CAAA;AACtD;;GAEG;AACH,MAAqB,KAAK;IAkBjB,MAAM,CAAC,UAAU,CACtB,MAA4B;QAE5B,OAAO,EAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;IACzC,CAAC;IAEO,MAAM,CAAO,iBAAiB,CACpC,MAA4B;;YAE5B,IAAI,MAAM,CAAC,WAAW;gBAAE,OAAO,EAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAA;;gBAC9D,OAAO,EAAK,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAA;QACjD,CAAC;KAAA;IAED;;;;;;OAMG;IACK,MAAM,CAAO,qBAAqB,CACxC,MAA4B;;YAE5B,OAAO,CAAC,KAAK,CAAC,yCAAyC,CAAC,CAAA;YACxD,MAAM,UAAU,GAAG,EAAK,CAAC,aAAa,+BACpC,QAAQ,EAAE,MAAM,CAAC,QAAQ,IACtB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,C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1
+ import Redis from './Redis.js';
2
+ /**
3
+ * Defines a type alias for specifying the cache type as 'redis'.
4
+ */
5
+ export type CacheType = 'redis';
6
+ /**
7
+ * Defines a CacheClass type that has a 'redis' property which is a constructor function
8
+ * that takes in any number of arguments and returns an instance of Redis.
9
+ */
10
+ export type CacheClass = {
11
+ redis: new (...args: any[]) => Redis;
12
+ };
13
+ /**
14
+ * Represents the base configuration for a cache, including host, username, password, and TLS settings.
15
+ */
16
+ export type CacheBaseConfig = {
17
+ hostname: string;
18
+ username: string;
19
+ password?: string;
20
+ enableTLS: boolean;
21
+ clusterMode?: boolean;
22
+ };
23
+ /**
24
+ * Defines a CacheConfig type that extends CacheBaseConfig and includes a specific cache type.
25
+ * @template S - The specific cache type to be included in the CacheConfig.
26
+ * @extends CacheBaseConfig
27
+ * @property {S} type - The specific cache type included in the CacheConfig.
28
+ */
29
+ export type CacheConfig<S extends CacheType> = CacheBaseConfig & {
30
+ type: S;
31
+ };