@ikonintegration/ikapi 4.0.1 → 5.0.0

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 (236) 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/README.md +89 -99
  6. package/dist/index.d.ts +16 -0
  7. package/dist/index.js +27 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/package-lock.json +11881 -0
  10. package/dist/package.json +81 -0
  11. package/dist/src/API/Request.d.ts +125 -0
  12. package/dist/src/API/Request.js +185 -0
  13. package/dist/src/API/Request.js.map +1 -0
  14. package/dist/src/API/Response.d.ts +188 -0
  15. package/dist/src/API/Response.js +270 -0
  16. package/dist/src/API/Response.js.map +1 -0
  17. package/dist/src/BaseEvent/DynamoTransaction.d.ts +70 -0
  18. package/dist/src/BaseEvent/DynamoTransaction.js +104 -0
  19. package/dist/src/BaseEvent/DynamoTransaction.js.map +1 -0
  20. package/dist/src/BaseEvent/EventProcessor.d.ts +58 -0
  21. package/dist/src/BaseEvent/EventProcessor.js +101 -0
  22. package/dist/src/BaseEvent/EventProcessor.js.map +1 -0
  23. package/dist/src/BaseEvent/Process.d.ts +50 -0
  24. package/dist/src/BaseEvent/Process.js +64 -0
  25. package/dist/src/BaseEvent/Process.js.map +1 -0
  26. package/dist/src/BaseEvent/StepTransaction.d.ts +23 -0
  27. package/dist/src/BaseEvent/StepTransaction.js +27 -0
  28. package/dist/src/BaseEvent/StepTransaction.js.map +1 -0
  29. package/dist/src/BaseEvent/Transaction.d.ts +149 -0
  30. package/dist/src/BaseEvent/Transaction.js +224 -0
  31. package/dist/src/BaseEvent/Transaction.js.map +1 -0
  32. package/dist/src/Cache/Redis.d.ts +29 -0
  33. package/dist/src/Cache/Redis.js +80 -0
  34. package/dist/src/Cache/Redis.js.map +1 -0
  35. package/dist/src/Cache/types.d.ts +31 -0
  36. package/dist/src/Cache/types.js +2 -0
  37. package/dist/src/Cache/types.js.map +1 -0
  38. package/dist/src/Config/Configuration.d.ts +123 -0
  39. package/dist/src/Config/Configuration.js +109 -0
  40. package/dist/src/Config/Configuration.js.map +1 -0
  41. package/dist/src/Config/EnvironmentVar.d.ts +74 -0
  42. package/dist/src/Config/EnvironmentVar.js +138 -0
  43. package/dist/src/Config/EnvironmentVar.js.map +1 -0
  44. package/dist/src/Crypto/Crypto.d.ts +45 -0
  45. package/dist/src/Crypto/Crypto.js +72 -0
  46. package/dist/src/Crypto/Crypto.js.map +1 -0
  47. package/dist/src/Database/Database.d.ts +21 -0
  48. package/dist/src/Database/Database.js +15 -0
  49. package/dist/src/Database/Database.js.map +1 -0
  50. package/dist/src/Database/DatabaseManager.d.ts +47 -0
  51. package/dist/src/Database/DatabaseManager.js +60 -0
  52. package/dist/src/Database/DatabaseManager.js.map +1 -0
  53. package/dist/src/Database/DatabaseTransaction.d.ts +101 -0
  54. package/dist/src/Database/DatabaseTransaction.js +126 -0
  55. package/dist/src/Database/DatabaseTransaction.js.map +1 -0
  56. package/dist/src/Database/index.d.ts +10 -0
  57. package/dist/src/Database/index.js +15 -0
  58. package/dist/src/Database/index.js.map +1 -0
  59. package/dist/src/Database/integrations/dynamo/DynamoDatabase.d.ts +35 -0
  60. package/dist/src/Database/integrations/dynamo/DynamoDatabase.js +59 -0
  61. package/dist/src/Database/integrations/dynamo/DynamoDatabase.js.map +1 -0
  62. package/dist/src/Database/integrations/kysely/KyselyDatabase.d.ts +66 -0
  63. package/dist/src/Database/integrations/kysely/KyselyDatabase.js +86 -0
  64. package/dist/src/Database/integrations/kysely/KyselyDatabase.js.map +1 -0
  65. package/dist/src/Database/integrations/kysely/KyselyTransaction.d.ts +70 -0
  66. package/dist/src/Database/integrations/kysely/KyselyTransaction.js +118 -0
  67. package/dist/src/Database/integrations/kysely/KyselyTransaction.js.map +1 -0
  68. package/dist/src/Database/integrations/pgsql/PostgresDatabase.d.ts +36 -0
  69. package/dist/src/Database/integrations/pgsql/PostgresDatabase.js +54 -0
  70. package/dist/src/Database/integrations/pgsql/PostgresDatabase.js.map +1 -0
  71. package/dist/src/Database/integrations/pgsql/PostgresTransaction.d.ts +63 -0
  72. package/dist/src/Database/integrations/pgsql/PostgresTransaction.js +61 -0
  73. package/dist/src/Database/integrations/pgsql/PostgresTransaction.js.map +1 -0
  74. package/dist/src/Database/types.d.ts +76 -0
  75. package/dist/src/Database/types.js +2 -0
  76. package/dist/src/Database/types.js.map +1 -0
  77. package/dist/src/Globals.d.ts +93 -0
  78. package/dist/src/Globals.js +99 -0
  79. package/dist/src/Globals.js.map +1 -0
  80. package/dist/src/Logger/Logger.d.ts +161 -0
  81. package/dist/src/Logger/Logger.js +299 -0
  82. package/dist/src/Logger/Logger.js.map +1 -0
  83. package/dist/src/Mailer/Mailer.d.ts +78 -0
  84. package/dist/src/Mailer/Mailer.js +182 -0
  85. package/dist/src/Mailer/Mailer.js.map +1 -0
  86. package/dist/src/Publisher/Publisher.d.ts +39 -0
  87. package/dist/src/Publisher/Publisher.js +77 -0
  88. package/dist/src/Publisher/Publisher.js.map +1 -0
  89. package/dist/src/Server/RouteResolver.d.ts +33 -0
  90. package/dist/src/Server/RouteResolver.js +100 -0
  91. package/dist/src/Server/RouteResolver.js.map +1 -0
  92. package/dist/src/Server/Router.d.ts +157 -0
  93. package/dist/src/Server/Router.js +32 -0
  94. package/dist/src/Server/Router.js.map +1 -0
  95. package/dist/src/Server/lib/ContainerServer.d.ts +42 -0
  96. package/dist/src/Server/lib/ContainerServer.js +66 -0
  97. package/dist/src/Server/lib/ContainerServer.js.map +1 -0
  98. package/dist/src/Server/lib/Server.d.ts +45 -0
  99. package/dist/src/Server/lib/Server.js +93 -0
  100. package/dist/src/Server/lib/Server.js.map +1 -0
  101. package/dist/src/Server/lib/container/GenericHandler.d.ts +9 -0
  102. package/dist/src/Server/lib/container/GenericHandler.js +82 -0
  103. package/dist/src/Server/lib/container/GenericHandler.js.map +1 -0
  104. package/dist/src/Server/lib/container/GenericHandlerEvent.d.ts +52 -0
  105. package/dist/src/Server/lib/container/GenericHandlerEvent.js +132 -0
  106. package/dist/src/Server/lib/container/GenericHandlerEvent.js.map +1 -0
  107. package/dist/src/Server/lib/container/HealthHandler.d.ts +9 -0
  108. package/dist/src/Server/lib/container/HealthHandler.js +19 -0
  109. package/dist/src/Server/lib/container/HealthHandler.js.map +1 -0
  110. package/dist/src/Server/lib/container/Proxy.d.ts +67 -0
  111. package/dist/src/Server/lib/container/Proxy.js +143 -0
  112. package/dist/src/Server/lib/container/Proxy.js.map +1 -0
  113. package/dist/src/Server/lib/container/Utils.d.ts +14 -0
  114. package/dist/src/Server/lib/container/Utils.js +37 -0
  115. package/dist/src/Server/lib/container/Utils.js.map +1 -0
  116. package/dist/src/Util/AsyncSingleton.d.ts +31 -0
  117. package/dist/src/Util/AsyncSingleton.js +83 -0
  118. package/dist/src/Util/AsyncSingleton.js.map +1 -0
  119. package/dist/src/Util/Utils.d.ts +61 -0
  120. package/dist/src/Util/Utils.js +147 -0
  121. package/dist/src/Util/Utils.js.map +1 -0
  122. package/dist/src/Validation/Validator.d.ts +17 -0
  123. package/dist/src/Validation/Validator.js +39 -0
  124. package/dist/src/Validation/Validator.js.map +1 -0
  125. package/dist/tsconfig.tsbuildinfo +1 -0
  126. package/index.ts +41 -0
  127. package/jest.config.ts +37 -0
  128. package/jest.smoke.config.ts +34 -0
  129. package/package.json +66 -22
  130. package/src/API/Request.ts +214 -0
  131. package/src/API/Response.ts +370 -0
  132. package/src/BaseEvent/DynamoTransaction.ts +175 -0
  133. package/src/BaseEvent/EventProcessor.ts +140 -0
  134. package/src/BaseEvent/Process.ts +78 -0
  135. package/src/BaseEvent/StepTransaction.ts +35 -0
  136. package/src/BaseEvent/Transaction.ts +323 -0
  137. package/src/Cache/Redis.ts +89 -0
  138. package/src/Cache/types.ts +33 -0
  139. package/src/Config/Configuration.ts +199 -0
  140. package/src/Config/EnvironmentVar.ts +142 -0
  141. package/src/Crypto/Crypto.ts +89 -0
  142. package/src/Database/Database.ts +22 -0
  143. package/src/Database/DatabaseManager.ts +67 -0
  144. package/src/Database/DatabaseTransaction.ts +170 -0
  145. package/src/Database/index.ts +27 -0
  146. package/src/Database/integrations/dynamo/DynamoDatabase.ts +58 -0
  147. package/src/Database/integrations/kysely/KyselyDatabase.ts +99 -0
  148. package/src/Database/integrations/kysely/KyselyTransaction.ts +172 -0
  149. package/src/Database/integrations/pgsql/PostgresDatabase.ts +56 -0
  150. package/src/Database/integrations/pgsql/PostgresTransaction.ts +87 -0
  151. package/src/Database/types.ts +85 -0
  152. package/src/Globals.ts +103 -0
  153. package/src/Logger/Logger.ts +363 -0
  154. package/src/Mailer/Mailer.ts +217 -0
  155. package/src/Publisher/Publisher.ts +96 -0
  156. package/src/Server/RouteResolver.ts +124 -0
  157. package/src/Server/Router.ts +200 -0
  158. package/src/Server/lib/ContainerServer.ts +65 -0
  159. package/src/Server/lib/Server.ts +109 -0
  160. package/src/Server/lib/container/GenericHandler.ts +76 -0
  161. package/src/Server/lib/container/GenericHandlerEvent.ts +154 -0
  162. package/src/Server/lib/container/HealthHandler.ts +11 -0
  163. package/src/Server/lib/container/Proxy.ts +172 -0
  164. package/src/Server/lib/container/Utils.ts +33 -0
  165. package/src/Util/AsyncSingleton.ts +86 -0
  166. package/src/Util/Utils.ts +131 -0
  167. package/src/Validation/Validator.ts +45 -0
  168. package/tests/API/Request.test.ts +273 -0
  169. package/tests/API/Response.test.ts +367 -0
  170. package/tests/BaseEvent/DynamoTransaction.test.ts +272 -0
  171. package/tests/BaseEvent/EventProcessor.test.ts +263 -0
  172. package/tests/BaseEvent/Process.test.ts +47 -0
  173. package/tests/BaseEvent/StepTransaction.test.ts +44 -0
  174. package/tests/BaseEvent/Transaction.test.ts +402 -0
  175. package/tests/Cache/Redis-client.test.ts +90 -0
  176. package/tests/Cache/Redis-cluster.test.ts +100 -0
  177. package/tests/Config/Config.test.ts +205 -0
  178. package/tests/Config/EnvironmentVar.test.ts +251 -0
  179. package/tests/Crypto/Crypto.test.ts +88 -0
  180. package/tests/Database/DatabaseManager.test.ts +79 -0
  181. package/tests/Database/integrations/dynamo/DynamoDatabase.test.ts +44 -0
  182. package/tests/Database/integrations/kysely/KyselyDatabase.test.ts +113 -0
  183. package/tests/Database/integrations/kysely/KyselyTransaction.test.ts +119 -0
  184. package/tests/Database/integrations/pg/PostgresDatabase.test.ts +76 -0
  185. package/tests/Database/integrations/pg/PostgresTransaction.test.ts +118 -0
  186. package/tests/Logger/Logger.test.ts +215 -0
  187. package/tests/Mailer/Mailer.test.ts +59 -0
  188. package/tests/Publisher/Publisher.test.ts +60 -0
  189. package/tests/Server/RouteResolver.test.ts +116 -0
  190. package/tests/Server/Router.test.ts +39 -0
  191. package/tests/Server/lib/ContainerServer.test.ts +531 -0
  192. package/tests/Server/lib/Server.test.ts +12 -0
  193. package/tests/Server/lib/container/GenericHandler.test.ts +131 -0
  194. package/tests/Server/lib/container/GenericHandlerEvent.test.ts +103 -0
  195. package/tests/Server/lib/container/HealthHandler.test.ts +30 -0
  196. package/tests/Server/lib/container/Proxy.test.ts +268 -0
  197. package/tests/Server/lib/container/Utils.test.ts +47 -0
  198. package/tests/Test.utils.ts +78 -0
  199. package/tests/Utils/Utils.test.ts +229 -0
  200. package/tests/Validation/Validator.test.ts +82 -0
  201. package/tsconfig.json +26 -0
  202. package/tsconfig.smoke.json +26 -0
  203. package/index.js +0 -88
  204. package/src/API/IKRequest.js +0 -52
  205. package/src/API/IKResponse.js +0 -119
  206. package/src/API/IKUtils.js +0 -51
  207. package/src/BaseEvent/IKProcess.js +0 -77
  208. package/src/BaseEvent/IKTransaction.js +0 -139
  209. package/src/Cache/Prototype/IKCache.js +0 -17
  210. package/src/Cache/Redis/IKRedis.js +0 -148
  211. package/src/Database/DDB/IKDB.js +0 -56
  212. package/src/Database/DDB/IKDBBaseExpression.js +0 -130
  213. package/src/Database/DDB/IKDBBaseQuery.js +0 -151
  214. package/src/Database/DDB/IKDBQueryBatchGet.js +0 -37
  215. package/src/Database/DDB/IKDBQueryBatchWrite.js +0 -64
  216. package/src/Database/DDB/IKDBQueryDelete.js +0 -34
  217. package/src/Database/DDB/IKDBQueryGet.js +0 -48
  218. package/src/Database/DDB/IKDBQueryPut.js +0 -87
  219. package/src/Database/DDB/IKDBQueryScan.js +0 -45
  220. package/src/Database/DDB/IKDBQueryTransactionalWrite.js +0 -69
  221. package/src/Database/DDB/IKDBQueryUpdate.js +0 -221
  222. package/src/Database/DDB/_IKDBQueryTransactionalRead.js +0 -46
  223. package/src/Database/PSQL/IKDB.js +0 -41
  224. package/src/Database/PSQL/IKDBBaseQuery.js +0 -26
  225. package/src/Database/Prototype/IKDB.js +0 -21
  226. package/src/Database/Prototype/IKDBBaseQuery.js +0 -14
  227. package/src/IKDynamoStream.js +0 -42
  228. package/src/IKEventProcessor.js +0 -42
  229. package/src/IKGlobals.js +0 -24
  230. package/src/IKRouter.js +0 -47
  231. package/src/IKStepTransaction.js +0 -14
  232. package/src/Logger/IKLogger.js +0 -136
  233. package/src/Mailer/IKMailer.js +0 -69
  234. package/src/Publisher/IKPublisher.js +0 -44
  235. package/src/Tracker/IKExecutionTracker.js +0 -79
  236. package/src/Validation/IKValidation.js +0 -76
@@ -1,77 +0,0 @@
1
- //
2
- import IKGlobals from '../IKGlobals.js';
3
- import Utils from "../API/IKUtils.js";
4
- //Database
5
- import IKDBDDB from "../Database/DDB/IKDB.js";
6
- import IKDBPSQL from "../Database/PSQL/IKDB.js";
7
- //Cache
8
- import IKCacheRedis from '../Cache/Redis/IKRedis.js';
9
- //Comps
10
- import IKLogger from "../Logger/IKLogger.js";
11
- import IKValidation from '../Validation/IKValidation.js';
12
- import IKPublisher from '../Publisher/IKPublisher.js';
13
- import IKExecutionTracker from '../Tracker/IKExecutionTracker.js';
14
- //
15
- export default class IKProcess {
16
- constructor(config, interval) {
17
- this._config = config;
18
- this.allowExecutionIdentification = false;
19
- this.interval = interval;
20
- this.logger = new IKLogger(config.logger, Utils.logLevel());
21
- this.publisher = new IKPublisher(config.publisher);
22
- this.validator = new IKValidation(config.validation);
23
- this.db = this._getDBDriver();
24
- this.cache = this._getCacheDriver();
25
- if (config.resourcesTracker) this.tracker = new IKExecutionTracker(config.resourcesTracker, null, this.db);
26
- }
27
-
28
- //Main interface
29
- async execute(executionFunc) {
30
- this.logger.debug("Starting main process code");
31
- //Tracker
32
- if (this.allowExecutionIdentification && this.tracker) this.tracker.resetExecutionTrace();
33
- //Connect DB
34
- if (this.db) await this.db.connect();
35
- //Program loop
36
- setInterval( async () => {
37
- await this._execute(executionFunc);
38
- }, this.interval);
39
- //Tracker
40
- if (this.allowExecutionIdentification && this.tracker) await this.tracker.trackExecAndDrain();
41
- }
42
- //Executions
43
- async _execute(executionFunc) {
44
- let executionFailed = true; //failled til we say no!
45
- //safe execution handler
46
- try {
47
- //start DB transaction
48
- if (this.db) await this.db.beginTransaction();
49
- //Execute
50
- await executionFunc(this);
51
- //Commit DB
52
- if (this.db) await this.db.commit();
53
- //Tracker
54
- if (this.tracker) await this.tracker.quickDrain();
55
- //
56
- executionFailed = false;
57
- } catch (e) { /*EXECUTION FAIL*/
58
- this.logger.error('Exception when executing main request code. Rolling back DB!');
59
- this.logger.exception(e);
60
- //Rollback DB
61
- if (this.db) await this.db.rollback();
62
- } return executionFailed;
63
- }
64
- /* DB drivers support */
65
- _getDBDriver() {
66
- if (this._config.database) {
67
- if (this._config.database.type == IKGlobals.DBDrivers.PSQL) return new IKDBPSQL(this._config.database, this);
68
- else if (Object.keys(this._config.database).length > 0) return new IKDBDDB(this._config.database, this);
69
- } return null;
70
- }
71
- /* Cache drivers support */
72
- _getCacheDriver() {
73
- if (this._config.cache) {
74
- if (this._config.cache.type == IKGlobals.CacheDrivers.REDIS) return new IKCacheRedis(this._config.cache, this);
75
- } return null;
76
- }
77
- }
@@ -1,139 +0,0 @@
1
- //
2
- import IKGlobals from '../IKGlobals.js';
3
- import Utils from "../API/IKUtils.js";
4
- //Database
5
- import IKDBDDB from "../Database/DDB/IKDB.js";
6
- import IKDBPSQL from "../Database/PSQL/IKDB.js";
7
- //Cache
8
- import IKCacheRedis from '../Cache/Redis/IKRedis.js';
9
- //Comps
10
- import IKLogger from "../Logger/IKLogger.js";
11
- import IKValidation from '../Validation/IKValidation.js';
12
- import IKPublisher from '../Publisher/IKPublisher.js';
13
- import IKExecutionTracker from '../Tracker/IKExecutionTracker.js';
14
- //Request
15
- import IKRequest from '../API/IKRequest.js';
16
- import IKResponse, { IKBadRequestResponseWithRollback } from '../API/IKResponse.js';
17
-
18
- //
19
- export default class IKTransaction {
20
- constructor(event, context, config, _isBatch, _retrowErrors) {
21
- this._event = event;
22
- this._context = context;
23
- this._config = config;
24
- //response behaviour flags
25
- this._syncReturn = _isBatch;
26
- this._retrowErrors = _retrowErrors; /* retrow internal errors */
27
- this._resp = null;
28
- //When set, this will be called with the response context right before calling the context suceed/fail - useful for IOing the resp for example.
29
- this.responseProxy = null;
30
- //
31
- this.logger = new IKLogger(config.logger, Utils.logLevel(), (context.awsRequestId ? context.awsRequestId : (event.requestContext ? event.requestContext.requestId : 'unknown')));
32
- this.request = new IKRequest(this._event, this._context, this);
33
- this.publisher = new IKPublisher(config.publisher);
34
- this.validator = new IKValidation(config.validation);
35
- this.db = this._getDBDriver();
36
- if (config.resourcesTracker) this.tracker = new IKExecutionTracker(config.resourcesTracker, context, this.db);
37
- this.cache = this._getCacheDriver();
38
- }
39
-
40
- //Main interface
41
- async execute(executionFunc) {
42
- await this._executeLoggerFlush(async ()=>{
43
- await this._executeDBTransactions(async ()=>{
44
- return await this._execute(executionFunc);
45
- });
46
- });
47
- if (this._syncReturn) return this._resp;
48
- }
49
- //Executions
50
- async _execute(executionFunc) {
51
- let executionFailed = true; //failled til we say no!
52
- //safe execution handler
53
- try { //Execute
54
- this.logger.debug("Starting main request code");
55
- this._resp = await executionFunc(this);
56
- //Tracker after successful execution (before succeeding the context, which will cause things to die)
57
- if (this.tracker) await this.tracker.trackExecAndDrain();
58
- //Answer client
59
- if (this._resp && this._resp instanceof IKResponse) {
60
- await this._resp.build(this._context, this, this._syncReturn);
61
- executionFailed = !!(this._resp.getBody() && this._resp.getBody().rollback);
62
- } else if (this._syncReturn && this._resp) { //sync return can return other than ikresponse
63
- this.logger.log("Sync return with different response object:");
64
- this.logger.debug(this._resp);
65
- executionFailed = false;
66
- } else {
67
- this._resp = this._getErrorResponse(IKGlobals.ErrorResponseInvalidServerResponse, IKGlobals.ErrorCode_APIError)
68
- await this._resp.build(this._context, this, this._syncReturn);
69
- this.logger.error("Invalid response object from main request code.");
70
- }
71
- } catch (e) { /*EXECUTION FAIL*/
72
- this.logger.error('Exception when executing main request code.');
73
- this.logger.exception(e);
74
- //retrow?
75
- if (this._retrowErrors) throw e;
76
- //envelope exception?
77
- if (executionFailed) {
78
- this._resp = this._getErrorResponse(IKGlobals.ErrorResponseUnhandledError, IKGlobals.ErrorCode_APIError);
79
- await this._resp.build(this._context, this, this._syncReturn);
80
- }
81
- } return executionFailed;
82
- }
83
- async _executeDBTransactions(safeExecution) {
84
- try {
85
- //start DB
86
- if (this.db) await this.db.connect();
87
- //start transaction
88
- if (this.db) await this.db.beginTransaction();
89
- //
90
- let executionFailed = await safeExecution();
91
- //Commit if not failed, rollback if failed
92
- if (!executionFailed) {
93
- if (this.db) await this.db.commit();
94
- } else {
95
- this.logger.log("Rolling back DB transactions. Main code failed!");
96
- if (this.db) await this.db.rollback();
97
- }
98
- //Cleanup DB after execution
99
- if (this.db) await this.db.cleanup();
100
- } catch (e) {
101
- this.logger.error('Exception when executing DB transactions.');
102
- this.logger.log(e.stack);
103
- //retrow?
104
- if (this._retrowErrors) throw e;
105
- }
106
- }
107
- async _executeLoggerFlush(safeExecution) {
108
- try {
109
- await safeExecution();
110
- await this.logger.flushLogs();
111
- //Tracker (if not tracked yet -- exception case)
112
- if (this.tracker) await this.tracker.trackExecAndDrain();
113
- } catch (e) {
114
- this.logger.error('Exception when flushing logs.');
115
- this.logger.exception(e);
116
- //retrow?
117
- if (this._retrowErrors) throw e;
118
- } finally {
119
- this.logger.debug("Transaction ended");
120
- }
121
- }
122
- /* DB drivers support */
123
- _getDBDriver() {
124
- if (this._config.database) {
125
- if (this._config.database.type == IKGlobals.DBDrivers.PSQL) return new IKDBPSQL(this._config.database, this);
126
- else if (Object.keys(this._config.database).length > 0) return new IKDBDDB(this._config.database, this);
127
- } return null;
128
- }
129
- /* Cache drivers support */
130
- _getCacheDriver() {
131
- if (this._config.cache) {
132
- if (this._config.cache.type == IKGlobals.CacheDrivers.REDIS) return new IKCacheRedis(this._config.cache, this);
133
- } return null;
134
- }
135
- /* Response support */
136
- _getErrorResponse(error, code) {
137
- return IKBadRequestResponseWithRollback(error, code);
138
- }
139
- }
@@ -1,17 +0,0 @@
1
- export default class IKCache {
2
- constructor(config, transaction) {
3
- this.config = config;
4
- this.transaction = transaction;
5
- this.connection = null;
6
- }
7
- /* Public */
8
- async get(key) { }
9
- async set(key, value) { }
10
- async del(key) { }
11
- async keys(pattern) { }
12
- async mget(key) { }
13
- async mset(key, value) { }
14
- async mdel(key) { }
15
- /* Private */
16
- async _connect() { }
17
- }
@@ -1,148 +0,0 @@
1
- import IKCache from '../Prototype/IKCache.js';
2
- export default class IKCache_Redis extends IKCache {
3
- constructor(config, transaction) {
4
- super(config, transaction);
5
- //
6
- this.awaitingConnectionQueue = null;
7
- //
8
- const localConsole = (transaction ? transaction.logger : console);
9
- if (config && config.host) { localConsole.debug(`Using cache: REDIS on host: ${config.host}`); }
10
- }
11
- /* Public */
12
- async get(key) {
13
- return new Promise(async (resolve, reject) => {
14
- await this._connect();
15
- this.connection.get(key, (err, reply) => {
16
- if (err) reject(err);
17
- else (resolve(reply));
18
- });
19
- });
20
- }
21
- async set(key, value) {
22
- return new Promise(async (resolve, reject) => {
23
- await this._connect();
24
- this.connection.set(key, value, (err, reply) => {
25
- if (err) reject(err);
26
- else (resolve(reply));
27
- });
28
- });
29
- }
30
- async del(key) {
31
- return new Promise(async (resolve, reject) => {
32
- await this._connect();
33
- this.connection.del(key, (err, reply) => {
34
- if (err) reject(err);
35
- else (resolve(reply));
36
- });
37
- });
38
- }
39
- async keys(pattern) {
40
- return new Promise(async (resolve, reject) => {
41
- await this._connect();
42
- this.connection.keys(pattern, (err, reply) => {
43
- if (err) reject(err);
44
- else (resolve(reply));
45
- });
46
- });
47
- }
48
- async mget() {
49
- return new Promise(async (resolve, reject) => {
50
- await this._connect();
51
- this.connection.mget(...arguments, (err, reply) => {
52
- if (err) reject(err);
53
- else (resolve(reply));
54
- });
55
- });
56
- }
57
- async mset() {
58
- return new Promise(async (resolve, reject) => {
59
- await this._connect();
60
- this.connection.mset(...arguments, (err, reply) => {
61
- if (err) reject(err);
62
- else (resolve(reply));
63
- });
64
- });
65
- }
66
- async mdel() {
67
- return new Promise(async (resolve, reject) => {
68
- await this._connect();
69
- this.connection.del(...arguments, (err, reply) => {
70
- if (err) reject(err);
71
- else (resolve(reply));
72
- });
73
- });
74
- }
75
- /* Private */
76
- async _isRedisClientAvailable() {
77
- let response = true;
78
- try { const test = await import('redis'); }
79
- catch (e) { response = false; }
80
- return response;
81
- }
82
- async _isRedisClientV4() {
83
- let isV4 = false;
84
- try {
85
- const test = await import('redis');
86
- isV4 = !!test.createCluster;
87
- }
88
- catch (e) { }
89
- return isV4;
90
- }
91
- async _connect() {
92
- //No connection, but waiting connection queue is valid? wait until other promise
93
- //fulfill this promire
94
- if (!this.connection && this.awaitingConnectionQueue) {
95
- return new Promise((resolve) => this.awaitingConnectionQueue.push(resolve));
96
- } else if (this.connection) return this.connection; //already connected
97
-
98
- //Check if redis client is available
99
- if (!(await this._isRedisClientAvailable())) throw new Error('Redis client is not available! Please, run "npm i -S redis".');
100
-
101
- //Prepare
102
- const localConsole = (this.transaction ? this.transaction.logger : console);
103
- this.awaitingConnectionQueue = [];
104
- localConsole.debug("Starting remote cache connection");
105
-
106
- //Instantiate client and initiate connection
107
- return new Promise(async (resolve, reject) => {
108
- const redis = await import("redis");
109
- const isV4 = await this._isRedisClientV4();
110
- //
111
- const connection = redis.createClient({
112
- ...(isV4 ? {
113
- username: this.config.user,
114
- socket: {
115
- ...(this.config.enableTLS ? { tls: true } : {}), host: this.config.host,
116
- connectTimeout: 10000, reconnectStrategy: (retries) => retries <= 2 ? 1000 : new Error('Redis max connection attempts reached!')
117
- }
118
- } : {
119
- host: this.config.host, user: this.config.user,
120
- ...(this.config.enableTLS ? { tls: {} } /* https://docs.upstash.com/howto/connectwithtls */ : {})
121
- }),
122
- password: this.config.password,
123
- });
124
- //redis v4 & v3 compatibility
125
- if (connection && connection.connect) await connection.connect();
126
- //
127
- const connectedHandler = () => {
128
- this.connection = connection;
129
- if (this.awaitingConnectionQueue) this.awaitingConnectionQueue.forEach((resolve) => resolve());
130
- this.awaitingConnectionQueue = null;
131
- resolve();
132
- }
133
- //reached here on v4, everything is connected
134
- if (isV4) {
135
- connectedHandler();
136
- return;
137
- }
138
- //v3 <=
139
- connection.on('connect', connectedHandler);
140
- connection.on('error', (err) => {
141
- localConsole.error(err);
142
- if (this.awaitingConnectionQueue) this.awaitingConnectionQueue.forEach((resolve) => resolve()); //fulfill, error will be thrown
143
- this.awaitingConnectionQueue = null;
144
- reject(err);
145
- });
146
- });
147
- }
148
- }
@@ -1,56 +0,0 @@
1
- import { DynamoDB } from "@aws-sdk/client-dynamodb";
2
- import { NodeHttpHandler } from "@aws-sdk/node-http-handler";
3
- import Utils from "./../../API/IKUtils.js";
4
- import sha1 from 'sha1';
5
- //
6
- import IKGlobals from './../../IKGlobals.js';
7
- import IKDB from './../Prototype/IKDB.js';
8
- //
9
- import { Agent } from "https";
10
- //reusable connection
11
- var DDB_CONN = null;
12
- var DDB_CONN_HASH = null;
13
- //
14
- export default class IKDB_DDB extends IKDB {
15
- constructor(config, transaction) {
16
- super(config, transaction);
17
- this.tableName = config.tableName;
18
- this.region = config.region;
19
- this.stats = { readUnits: 0, writeUnits: 0 };
20
- //
21
- // const localConsole = (transaction ? transaction.logger : console);
22
- // if (config && this.tableName) { localConsole.debug(`Using table: ${this.tableName} on region: ${this.region}`); }
23
- }
24
-
25
- async connect() {
26
- const localConsole = (this.transaction ? this.transaction.logger : console);
27
- //Reusability logic
28
- if (!((!DDB_CONN && !DDB_CONN_HASH) || DDB_CONN_HASH != sha1(this.region))) {
29
- localConsole.debug("Reusing database connection");
30
- this.connection = DDB_CONN;
31
- return;
32
- }
33
- //setup db
34
- if (Utils.isOffline()) {
35
- localConsole.debug("Starting offline database connection");
36
- this.connection = new DynamoDB(IKGlobals.DynamoDBLocalConfig);
37
- } else {
38
- // localConsole.debug("Starting remote database connection");
39
- //initialize connection
40
- this.connection = new DynamoDB({
41
- region: this.region, maxAttempts: IKGlobals.DDBMaxAttempts,
42
- requestHandler: new NodeHttpHandler({
43
- connectionTimeout: IKGlobals.DDBHttpTimeout, socketTimeout: IKGlobals.DDBHttpTimeout,
44
- httpsAgent: new Agent({ keepAlive: false, maxSockets: 50, rejectUnauthorized: true }),
45
- })
46
- });
47
- //Reusable logic
48
- DDB_CONN = this.connection;
49
- DDB_CONN_HASH = sha1(this.region);
50
- }
51
- }
52
- getTrackerStats() {
53
- if (!(this.stats.readUnits > 0 || this.stats.writeUnits > 0)) return null;
54
- return { tableName: this.tableName, ...this.stats };
55
- }
56
- }
@@ -1,130 +0,0 @@
1
- import Utils from './../../API/IKUtils.js';
2
- //
3
- export default class IKDBBaseExpression {
4
- constructor() {
5
- this.values = [];
6
- this.operator = IKDBExpressionOperator.AND;
7
- this.counter = 0;
8
- }
9
- /*public methods*/
10
- appendOperator(key, val, cond) {
11
- const aKey = this._anonimizeKeyValue(key);
12
- const keyName = this._anonimizeKeyName(key);
13
- this.values.push({exp: `${keyName} ${cond} ${aKey}`, values: [val], appendKeys: [aKey],
14
- anonimizedNames: { [keyName]: key }});
15
- }
16
- appendBetween(key, val1, val2) {
17
- const aKey = this._anonimizeKeyValue(key);
18
- const aKey2 = this._anonimizeKeyValue(key);
19
- const keyName = this._anonimizeKeyName(key);
20
- this.values.push({exp: `(${keyName} BETWEEN ${aKey} AND ${aKey2})`, values: [val1, val2], appendKeys: [aKey, aKey2],
21
- anonimizedNames: { [keyName]: key }});
22
- }
23
- appendBeginsWith(key, val) {
24
- const aKey = this._anonimizeKeyValue(key);
25
- const keyName = this._anonimizeKeyName(key);
26
- this.values.push({exp: `begins_with(${keyName}, ${aKey})`, values: [val], appendKeys: [aKey],
27
- anonimizedNames: { [keyName]: key }});
28
- }
29
- appendAttributeType(key, val) {
30
- const aKey = this._anonimizeKeyValue(key);
31
- const keyName = this._anonimizeKeyName(key);
32
- this.values.push({exp: `attribute_type(${keyName}, ${aKey})`, values: [val], appendKeys: [aKey],
33
- anonimizedNames: { [keyName]: key }});
34
- }
35
- appendContains(key, val) {
36
- const aKey = this._anonimizeKeyValue(key);
37
- const keyName = this._anonimizeKeyName(key);
38
- this.values.push({exp: `contains(${keyName}, ${aKey})`, values: [val], appendKeys: [aKey],
39
- anonimizedNames: { [keyName]: key }});
40
- }
41
- appendExists(key) {
42
- const keyName = this._anonimizeKeyName(key);
43
- this.values.push({exp: `attribute_exists(${keyName})`, anonimizedNames: { [keyName]: key } });
44
- }
45
- appendNotExists(key) {
46
- const keyName = this._anonimizeKeyName(key);
47
- this.values.push({exp: `attribute_not_exists(${keyName})`, anonimizedNames: { [keyName]: key } });
48
- }
49
- appendIN(key, values) {
50
- let aKeys = values.map((val)=>this._anonimizeKeyValue(val));
51
- const keyName = this._anonimizeKeyName(key);
52
- this.values.push({exp: `(${keyName} IN (${aKeys.toString()}))`, values: values, appendKeys: aKeys,
53
- anonimizedNames: { [keyName]: key }});
54
- }
55
- appendNotIN(key, values) {
56
- let aKeys = values.map((val)=>this._anonimizeKeyValue(val));
57
- const keyName = this._anonimizeKeyName(key);
58
- this.values.push({exp: `NOT (${keyName} IN (${aKeys.toString()}))`, values: values, appendKeys: aKeys,
59
- anonimizedNames: { [keyName]: key }});
60
- }
61
- _anonimizeKeyValue(_key) {
62
- this.counter++;
63
- return (':' + _key.replace(/[:-]/g, '') + this.counter);
64
- }
65
- _anonimizeKeyName(_key) {
66
- this.counter++;
67
- return ('#' + _key.replace(/[:-]/g, '') + this.counter);
68
- }
69
- //Groups
70
- startGroupping() { this.values.push({startGroupping: true}); }
71
- endGroupping() { this.values.push({endGroupping: true}); }
72
- addSeparator(val) { this.values.push({exp: ` ${val} `}); }
73
- //Builds items and exp (if set)
74
- buildExpression() {
75
- const exp = this.__buildExpressionOnQuery();
76
- // if (exp && Object.keys(exp).length > 0) console.debug('Building query expression..', exp);
77
- return exp;
78
- }
79
- __buildExpressionOnQuery() {
80
- let expression = {};
81
- if (this.values.length > 0) {
82
- //Check required values
83
- if (!expression.items) expression.items = {};
84
- if (!expression.names) expression.names = {};
85
- //build conditional expression
86
- let condition = '';
87
- let groupping = false;
88
- let keyCount = 0;
89
- for (let addObj of this.values) {
90
- if (condition != '' && !groupping) condition += ` ${this.operator} `;
91
- //Check for include types
92
- if (addObj.startGroupping) {
93
- condition += `(`;
94
- groupping = true;
95
- } else if (addObj.endGroupping) {
96
- condition += `)`;
97
- groupping = false;
98
- } else if (addObj.values) { //multi value expressions
99
- condition += `${addObj.exp}`;
100
- let i = 0;
101
- for (let val of addObj.values) {
102
- expression.items[`${addObj.appendKeys[i]}`] = Utils.encapsulateForDB(val);
103
- i++;
104
- }
105
- } else if (addObj.exp) { //pure expressions
106
- condition += `${addObj.exp}`;
107
- }
108
- //Check for key anonimization
109
- if (addObj.anonimizedNames) {
110
- for (let aKeyName of Object.keys(addObj.anonimizedNames)) {
111
- expression.names[aKeyName] = addObj.anonimizedNames[aKeyName];
112
- }
113
- }
114
- } expression.exp = condition;
115
- } return expression;
116
- }
117
- }
118
- //
119
- export const IKDBExpressionOperator = {
120
- EQUAL: '=',
121
- NOT_EQUAL: '<>',
122
- LESS_THAN: '<',
123
- LESS_EQUAL_THAN: '<=',
124
- GREATER_THAN: '>',
125
- GREATER_EQUAL_THAN: '>=',
126
- GREATE_EQUAL_THAN: '>=', //typo compatiblity :/
127
- NOT: 'NOT',
128
- AND: 'AND',
129
- OR: 'OR'
130
- };