@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,270 @@
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 Globals from '../Globals.js';
11
+ /**
12
+ * CustomError class that extends the built-in Error class.
13
+ * @class
14
+ * @extends Error
15
+ * @param {any} body - The body of the error, which can be an object or a string.
16
+ * @constructor
17
+ * @property {string} name - The name of the error.
18
+ */
19
+ class CustomError extends Error {
20
+ constructor(body) {
21
+ super(body.message || 'Unknown error!');
22
+ this.name = body.error || 'UnknownError';
23
+ }
24
+ }
25
+ /**
26
+ * Represents a response object with various methods for building and manipulating the response.
27
+ * @template BodyType - The type of the response body.
28
+ */
29
+ export default class Response {
30
+ /**
31
+ * Constructs a new Response object with the given status code, body, and optional behavior.
32
+ * @param {number} statusCode - The HTTP status code of the response.
33
+ * @param {BodyType} body - The body of the response.
34
+ * @param {Object} [optBehaviour] - Optional behavior configuration for the response.
35
+ * @param {boolean} [optBehaviour.shouldStream] - Indicates whether the response should be streamed.
36
+ * @param {boolean} [optBehaviour.rawBody] - Indicates whether the response body should be treated as raw data.
37
+ * @param {boolean} [optBehaviour.throwOnErrors] - Indicates whether errors should be thrown for non-successful status codes.
38
+ * @param {boolean} [optBehaviour
39
+ */
40
+ constructor(statusCode, body, optBehaviour) {
41
+ // response
42
+ this.statusCode = statusCode;
43
+ this.body = body;
44
+ this.headers = {
45
+ 'Access-Control-Allow-Origin': '*',
46
+ 'Access-Control-Allow-Credentials': true,
47
+ 'Content-Type': 'application/json',
48
+ };
49
+ // behaviour
50
+ this.isPipingOut = false; //internal -- flag to indicate streaming out has started and avoid double stream call
51
+ // options
52
+ this.shouldStream = !!(optBehaviour === null || optBehaviour === void 0 ? void 0 : optBehaviour.shouldStream); //
53
+ this.rawBody = !!(optBehaviour === null || optBehaviour === void 0 ? void 0 : optBehaviour.rawBody);
54
+ this.throwOnErrors = !!(optBehaviour === null || optBehaviour === void 0 ? void 0 : optBehaviour.throwOnErrors);
55
+ this.disableTransactionID = !!(optBehaviour === null || optBehaviour === void 0 ? void 0 : optBehaviour.disableTransactionID);
56
+ }
57
+ /**
58
+ * Get the status code of the response.
59
+ * @returns {number} The status code.
60
+ */
61
+ getCode() {
62
+ return this.statusCode;
63
+ }
64
+ /**
65
+ * Get the body of the object.
66
+ * @returns {BodyType} The body of the object.
67
+ */
68
+ getBody() {
69
+ return this.body;
70
+ }
71
+ /**
72
+ * Appends a key-value pair into the body object.
73
+ * @param {string} key - The key to append.
74
+ * @param {any} value - The value to append.
75
+ * @returns None
76
+ */
77
+ appendIntoBody(key, value) {
78
+ this.body[key] = value;
79
+ }
80
+ /**
81
+ * Appends a header to the existing headers object.
82
+ * @param {string} key - The key of the header.
83
+ * @param {any} value - The value of the header.
84
+ * @returns None
85
+ */
86
+ appendHeader(key, value) {
87
+ this.headers[key] = value;
88
+ }
89
+ /**
90
+ * Builds the response for the given context and transaction.
91
+ * @param {Context} context - The context object.
92
+ * @param {Transaction<any, any, any>} transaction - The transaction object.
93
+ * @param {boolean} optDoNotCallContext - Optional flag to indicate whether to call the context or not.
94
+ * @returns {Promise<void>} - A promise that resolves when the response is built.
95
+ */
96
+ build(context, transaction, optDoNotCallContext) {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ //Stream support
99
+ if (this.isPipingOut)
100
+ return;
101
+ if (this.shouldStream)
102
+ return this.pipe(context);
103
+ //append default fields
104
+ if (transaction.request.getRequestID() && this.body && !this.disableTransactionID)
105
+ this.appendIntoBody('transactionID', transaction.request.getRequestID()); //append transaction ID
106
+ //Raw response support
107
+ if (this.rawBody)
108
+ return this.rawContext(context, transaction);
109
+ //build response
110
+ const b = Object.assign({ statusCode: this.statusCode, headers: this.headers }, (this.body ? { body: JSON.stringify(this.body) } : {}));
111
+ //log response and respond to context
112
+ transaction.logger.debug(b);
113
+ //Check for transaction response proxy
114
+ if (transaction.responseProxy)
115
+ yield transaction.responseProxy(this);
116
+ //Batch does not succeed directly just on upper transaction (which will should be a batch)
117
+ if (!optDoNotCallContext)
118
+ context.succeed(b);
119
+ });
120
+ }
121
+ /**
122
+ * Private method that pipes the response to the given context.
123
+ * @param {Context} context - The context object provided by AWS Lambda.
124
+ * @returns None
125
+ */
126
+ pipe(context) {
127
+ //Check if not streaming
128
+ this.isPipingOut = true;
129
+ //build response
130
+ const b = {
131
+ statusCode: this.statusCode,
132
+ body: this.body,
133
+ headers: this.headers,
134
+ };
135
+ //log response and respond to context
136
+ context.succeed(b);
137
+ }
138
+ /**
139
+ * Private method that handles the raw context of a transaction.
140
+ * @param {Context} context - The context object.
141
+ * @param {Transaction<null, BodyType>} transaction - The transaction object.
142
+ * @returns None
143
+ */
144
+ rawContext(context, transaction) {
145
+ //log response and respond to context
146
+ transaction.logger.debug(this.body);
147
+ if (this.getCode() <= 200 && this.getCode() <= 299)
148
+ context.succeed(this.body);
149
+ else {
150
+ if (!this.throwOnErrors)
151
+ context.fail(new CustomError(this.body));
152
+ else
153
+ throw new CustomError(this.body);
154
+ }
155
+ }
156
+ /**
157
+ * Generates a response object for a missing path parameter error.
158
+ * @param {string} paramName - The name of the missing path parameter.
159
+ * @returns {Response<ResponseErrorType>} - The response object with error details.
160
+ */
161
+ static MissingParamResponse(paramName) {
162
+ console.warn(`Invalid request - Path parameter ${paramName} is missing.`);
163
+ return new Response(400, {
164
+ err: `Invalid request. Path parameter ${paramName} is missing.`,
165
+ errCode: Globals.ErrorCode_MissingParam,
166
+ });
167
+ }
168
+ /**
169
+ * Creates a response object for a missing query parameter error.
170
+ * @param {string} paramName - The name of the missing query parameter.
171
+ * @returns {Response<ResponseErrorType>} - The response object with error details.
172
+ */
173
+ static MissingQueryResponse(paramName) {
174
+ console.warn(`Invalid request - Query parameter ${paramName} is missing.`);
175
+ return new Response(400, {
176
+ err: `Invalid request. Query parameter ${paramName} is missing.`,
177
+ errCode: Globals.ErrorCode_MissingParam,
178
+ });
179
+ }
180
+ /**
181
+ * Creates a BadRequestResponse object with the given parameters.
182
+ * @param {string} [msg] - The error message.
183
+ * @param {string} [errCode] - The error code.
184
+ * @param {any} [optBody] - Optional additional body data.
185
+ * @returns {Response<ResponseErrorType>} - The BadRequestResponse object.
186
+ */
187
+ static BadRequestResponse(msg, errCode, optBody) {
188
+ console.warn(`Bad request - ${msg}`);
189
+ return new Response(400, Object.assign(Object.assign({ err: msg }, (errCode ? { errCode: errCode } : {})), (optBody || {})));
190
+ }
191
+ /**
192
+ * Creates a BadRequestResponse object with rollback option.
193
+ * @param {string} msg - The error message.
194
+ * @param {string} [errCode] - The error code.
195
+ * @param {any} [optBody] - Optional body to include in the response.
196
+ * @returns {Response<ResponseErrorType>} - The BadRequestResponse object.
197
+ */
198
+ static BadRequestResponseWithRollback(msg, errCode, optBody) {
199
+ console.warn(`Bad request - ${msg}`);
200
+ return new Response(400, Object.assign(Object.assign({ err: msg, rollback: true }, (errCode ? { errCode: errCode } : {})), (optBody || {})));
201
+ }
202
+ /**
203
+ * Creates an unauthorized response with the given error message and error code.
204
+ * @param {string} msg - The error message.
205
+ * @param {string} [errCode] - The error code (optional).
206
+ * @returns {Response<ResponseErrorType>} - The unauthorized response.
207
+ */
208
+ static UnauthorizedResponse(msg, errCode) {
209
+ console.warn(`Denying request - ${msg}`);
210
+ return new Response(401, Object.assign({ err: msg }, (errCode ? { errCode: errCode } : {})));
211
+ }
212
+ /**
213
+ * Creates a success response object with the given body.
214
+ * @param {BodyType} body - The body of the response.
215
+ * @returns {Response<BodyType>} - The success response object.
216
+ */
217
+ static SuccessResponse(body) {
218
+ return new Response(200, (body ? body : {}));
219
+ }
220
+ /**
221
+ * Creates a redirect response with the specified URL.
222
+ * @param {string} url - The URL to redirect to.
223
+ * @returns {Response<null>} - The redirect response.
224
+ */
225
+ static RedirectResponse(url) {
226
+ const resp = new Response(302, null);
227
+ resp.appendHeader('Location', url);
228
+ return resp;
229
+ }
230
+ /**
231
+ * Creates a success response with no content.
232
+ * @returns {Response<null>} A response object with a status code of 204 and no content.
233
+ */
234
+ static SuccessNoContentResponse() {
235
+ return new Response(204, null);
236
+ }
237
+ /**
238
+ * Creates a success response object with a streaming body and specified content type.
239
+ * @param {any} stream - The stream object to be used as the response body.
240
+ * @param {string} contentType - The content type of the response.
241
+ * @returns {Response} - The success response object.
242
+ */
243
+ static SuccessStreamResponse(stream, contentType) {
244
+ const resp = new Response(200, stream, {
245
+ shouldStream: true,
246
+ });
247
+ resp.appendHeader('Connection', 'keep-alive');
248
+ if (contentType)
249
+ resp.appendHeader('Content-Type', contentType);
250
+ return resp;
251
+ }
252
+ /**
253
+ * Creates a simple HTTP response with the given body and optional status code.
254
+ * @param {BodyType} body - The body of the response.
255
+ * @param {number} [optionalCode] - The optional status code of the response. Defaults to 200.
256
+ * @returns {Response<BodyType>} - The created response object.
257
+ */
258
+ static SimpleResponse(body, optionalCode) {
259
+ const resp = new Response(optionalCode || 200, body);
260
+ return resp;
261
+ }
262
+ static StepFunctionResponse(body, optionalCode) {
263
+ const resp = new Response(optionalCode || 200, body, {
264
+ rawBody: true,
265
+ throwOnErrors: true,
266
+ });
267
+ return resp;
268
+ }
269
+ }
270
+ //# sourceMappingURL=Response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Response.js","sourceRoot":"","sources":["../../../src/API/Response.ts"],"names":[],"mappings":";;;;;;;;;AAGA,OAAO,OAAO,MAAM,eAAe,CAAA;AAEnC;;;;;;;GAOG;AACH,MAAM,WAAY,SAAQ,KAAK;IAC7B,YAAY,IAAS;QACnB,KAAK,CAAC,IAAI,CAAC,OAAO,IAAI,gBAAgB,CAAC,CAAA;QACvC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,KAAK,IAAI,cAAc,CAAA;IAC1C,CAAC;CACF;AAaD;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,QAAQ;IA4C3B;;;;;;;;;OASG;IACH,YACE,UAAkB,EAClB,IAAc,EACd,YAOa;QAEb,WAAW;QACX,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAA;QAChB,IAAI,CAAC,OAAO,GAAG;YACb,6BAA6B,EAAE,GAAG;YAClC,kCAAkC,EAAE,IAAI;YACxC,cAAc,EAAE,kBAAkB;SACnC,CAAA;QACD,YAAY;QACZ,IAAI,CAAC,WAAW,GAAG,KAAK,CAAA,CAAC,qFAAqF;QAC9G,UA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I,MAAM,CAAC,qBAAqB,CAAC,MAAW,EAAE,WAAmB;QAClE,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE;YACrC,YAAY,EAAE,IAAI;SACnB,CAAC,CAAA;QACF,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,YAAY,CAAC,CAAA;QAC7C,IAAI,WAAW;YAAE,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,WAAW,CAAC,CAAA;QAC/D,OAAO,IAAI,CAAA;IACb,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,cAAc,CAC1B,IAAc,EACd,YAAqB;QAErB,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAW,YAAY,IAAI,GAAG,EAAE,IAAI,CAAC,CAAA;QAC9D,OAAO,IAAI,CAAA;IACb,CAAC;IAEM,MAAM,CAAC,oBAAoB,CAAW,IAAc,EAAE,YAAqB;QAChF,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAW,YAAY,IAAI,GAAG,EAAE,IAAI,EAAE;YAC7D,OAAO,EAAE,IAAI;YACb,aAAa,EAAE,IAAI;SACpB,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;CACF"}
@@ -0,0 +1,20 @@
1
+ import type { Context, DynamoDBBatchResponse, DynamoDBRecord, DynamoDBStreamEvent } from 'aws-lambda';
2
+ import Transaction, { TransactionConfig } from './Transaction.js';
3
+ import Response, { ResponseErrorType } from '../API/Response.js';
4
+ export interface DynamoDBMarshalledRecord extends DynamoDBRecord {
5
+ marshalled: {
6
+ Keys?: object;
7
+ OldImage?: object;
8
+ NewImage?: object;
9
+ };
10
+ }
11
+ export type DynamoTransactionExecution<ResponseInnerType> = (transaction: Transaction<null, ResponseInnerType | ResponseErrorType, DynamoDBBatchResponse | null>, recordContent: DynamoDBMarshalledRecord) => Promise<Response<ResponseInnerType | ResponseErrorType> | DynamoDBBatchResponse | null>;
12
+ export default class DynamoTransaction<ResponseInnerType> {
13
+ private readonly allowFailure;
14
+ private readonly config;
15
+ private readonly context;
16
+ private readonly event;
17
+ constructor(event: DynamoDBStreamEvent, context: Context, config?: TransactionConfig, allowFailure?: boolean);
18
+ processEvent(execution: DynamoTransactionExecution<ResponseInnerType>): Promise<Response<ResponseErrorType | null> | null | DynamoDBBatchResponse>;
19
+ private processRawEvent;
20
+ }
@@ -0,0 +1,81 @@
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 Transaction from './Transaction.js';
11
+ import Response from '../API/Response.js';
12
+ import Globals from '../Globals.js';
13
+ import Utils from '../Util/Utils.js';
14
+ export default class DynamoTransaction {
15
+ constructor(event, context, config, allowFailure) {
16
+ this.event = event;
17
+ this.context = context;
18
+ this.config = config || {};
19
+ this.allowFailure = !!allowFailure;
20
+ }
21
+ processEvent(execution) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ const resp = yield this.processRawEvent(execution);
24
+ if (!this.allowFailure &&
25
+ resp &&
26
+ resp instanceof Response &&
27
+ !(resp.getCode() >= 200 && resp.getCode() < 300))
28
+ throw new Error(JSON.stringify(resp.getBody() || {}));
29
+ else if (resp)
30
+ return resp;
31
+ return null;
32
+ });
33
+ }
34
+ processRawEvent(execution) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ var _a;
37
+ // safe check for empty events?
38
+ if (this.event.Records && this.event.Records.length > 0) {
39
+ // Regular cleanup of tmp disk to avoid tmp overflow on reused lambdas
40
+ if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.skipCleanTmp))
41
+ yield Utils.cleanTemporaryFolder();
42
+ // init transaction for all records
43
+ return yield new Transaction(this.event, this.context, Object.assign(Object.assign({}, this.config), { syncReturn: true })).execute((transaction) => __awaiter(this, void 0, void 0, function* () {
44
+ var _a, _b, _c, _d, _e, _f;
45
+ // for each available event
46
+ const failureIDs = [];
47
+ for (const eventRecordIdx in this.event.Records) {
48
+ const eventRecord = this.event.Records[eventRecordIdx];
49
+ const record = Object.assign(Object.assign({}, eventRecord), { marshalled: Object.assign(Object.assign(Object.assign({}, (((_a = eventRecord.dynamodb) === null || _a === void 0 ? void 0 : _a.Keys)
50
+ ? { Keys: Utils.ddbUnmarshall((_b = eventRecord.dynamodb) === null || _b === void 0 ? void 0 : _b.Keys) }
51
+ : {})), (((_c = eventRecord.dynamodb) === null || _c === void 0 ? void 0 : _c.OldImage)
52
+ ? { OldImage: Utils.ddbUnmarshall((_d = eventRecord.dynamodb) === null || _d === void 0 ? void 0 : _d.OldImage) }
53
+ : {})), (((_e = eventRecord.dynamodb) === null || _e === void 0 ? void 0 : _e.NewImage)
54
+ ? { NewImage: Utils.ddbUnmarshall((_f = eventRecord.dynamodb) === null || _f === void 0 ? void 0 : _f.NewImage) }
55
+ : {})) });
56
+ // Call execution with marshalled item
57
+ const resp = yield execution(transaction, record);
58
+ // check for failure
59
+ if (!resp ||
60
+ (resp instanceof Response && !((resp === null || resp === void 0 ? void 0 : resp.getCode()) >= 200 && (resp === null || resp === void 0 ? void 0 : resp.getCode()) < 300))) {
61
+ // response with failures or fail hard at first
62
+ if (this.allowFailure)
63
+ failureIDs.push(eventRecord.eventID);
64
+ else
65
+ return resp;
66
+ }
67
+ }
68
+ // not errored and loop ended - succeeded (might have failures)
69
+ if (this.allowFailure)
70
+ return {
71
+ batchItemFailures: failureIDs.map(id => ({ itemIdentifier: id })),
72
+ };
73
+ return Response.SuccessResponse(null);
74
+ }));
75
+ }
76
+ else
77
+ return Response.BadRequestResponse(Globals.ErrorResponseNoRecords, Globals.ErrorCode_NoRecords);
78
+ });
79
+ }
80
+ }
81
+ //# sourceMappingURL=DynamoTransaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DynamoTransaction.js","sourceRoot":"","sources":["../../../src/BaseEvent/DynamoTransaction.ts"],"names":[],"mappings":";;;;;;;;;AAOA,OAAO,WAAkC,MAAM,kBAAkB,CAAA;AACjE,OAAO,QAA+B,MAAM,oBAAoB,CAAA;AAChE,OAAO,OAAO,MAAM,eAAe,CAAA;AACnC,OAAO,KAAK,MAAM,kBAAkB,CAAA;AAmBpC,MAAM,CAAC,OAAO,OAAO,iBAAiB;IASpC,YACE,KAA0B,EAC1B,OAAgB,EAChB,MAA0B,EAC1B,YAAsB;QAEtB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,EAAE,CAAA;QAC1B,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,YAAY,CAAA;IACpC,CAAC;IAEY,YAAY,CACvB,SAAwD;;YAExD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,CAAA;YAClD,IACE,CAAC,IAAI,CAAC,YAAY;gBAClB,IAAI;gBACJ,IAAI,YAAY,QAAQ;gBACxB,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,GAAG,IAAI,IAAI,CAAC,OAAO,EAAE,GAAG,GAAG,CAAC;gBAEhD,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;iBAClD,IAAI,IAAI;gBAAE,OAAO,IAAI,CAAA;YAC1B,OAAO,IAAI,CAAA;QACb,CAAC;KAAA;IAEa,eAAe,CAC3B,SAAwD;;;YAExD,+BAA+B;YAC/B,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC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,CAAC,IAEV,CAAA;wBACD,sCAAsC;wBACtC,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,WAAW,EAAE,MAAM,CAAC,CAAA;wBACjD,oBAAoB;wBACpB,IACE,CAAC,IAAI;4BACL,CAAC,IAAI,YAAY,QAAQ,IAAI,CAAC,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAE,KAAI,GAAG,IAAI,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAE,IAAG,GAAG,CAAC,CAAC,EAChF,CAAC;4BACD,+CAA+C;4BAC/C,IAAI,IAAI,CAAC,YAAY;gCAAE,UAAU,CAAC,IAAI,CAAC,WAAW,CAAC,OAAQ,CAAC,CAAA;;gCACvD,OAAO,IAAI,CAAA;wBAClB,CAAC;oBACH,CAAC;oBACD,+DAA+D;oBAC/D,IAAI,IAAI,CAAC,YAAY;wBACnB,OAAO;4BACL,iBAAiB,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC,CAAC;yBAClE,CAAA;oBACH,OAAO,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,CAAA;gBACvC,CAAC,CAAA,CAAC,CAAA;YACJ,CAAC;;gBACC,OAAO,QAAQ,CAAC,kBAAkB,CAChC,OAAO,CAAC,sBAAsB,EAC9B,OAAO,CAAC,mBAAmB,CAC5B,CAAA;QACL,CAAC;KAAA;CACF"}
@@ -0,0 +1,58 @@
1
+ import type { Context, SQSBatchResponse, SQSEvent } from 'aws-lambda';
2
+ import Transaction, { TransactionConfig } from './Transaction.js';
3
+ import Response, { ResponseErrorType } from '../API/Response.js';
4
+ /**
5
+ * Type definition for an event processor execution function.
6
+ * @param {Transaction<null, ResponseInnerType | ResponseErrorType, SQSBatchResponse>} transaction - The transaction object.
7
+ * @param {string | object} recordContent - The content of the record being processed.
8
+ * @returns {Promise<Response<ResponseInnerType | ResponseErrorType> | SQSBatchResponse>} - A promise that resolves to the response or batch response.
9
+ */
10
+ export type EventProcessorExecution<ResponseInnerType> = (transaction: Transaction<null, ResponseInnerType | ResponseErrorType, SQSBatchResponse | null>, recordContent: string | object) => Promise<Response<ResponseInnerType | ResponseErrorType> | SQSBatchResponse | null>;
11
+ /**
12
+ * EventProcessor class that processes events from an SQS queue.
13
+ * @template ResponseInnerType - The type of the inner response object.
14
+ */
15
+ export default class EventProcessor<ResponseInnerType> {
16
+ /**
17
+ * A boolean flag indicating whether failures are allowed or not.
18
+ * @readonly
19
+ */
20
+ private readonly allowFailure;
21
+ /**
22
+ * The configuration object for the API transaction.
23
+ */
24
+ private readonly config;
25
+ /**
26
+ * The private readonly context property of the class.
27
+ * @type {Context}
28
+ */
29
+ private readonly context;
30
+ /**
31
+ * The SQS event object that triggered the Lambda function.
32
+ */
33
+ private readonly event;
34
+ /**
35
+ * Constructs a new instance of the class.
36
+ * @param {SQSEvent} event - The event object representing the incoming SQS message.
37
+ * @param {Context} context - The context object representing the AWS Lambda execution context.
38
+ * @param {TransactionConfig} [config] - Optional configuration object for the transaction.
39
+ * @param {boolean} [allowFailure] - Optional flag indicating whether to allow failure for the transaction.
40
+ * @returns None
41
+ */
42
+ constructor(event: SQSEvent, context: Context, config?: TransactionConfig, allowFailure?: boolean);
43
+ /**
44
+ * Processes an event using the provided execution object and returns a response.
45
+ * @param {EventProcessorExecution<ResponseInnerType>} execution - The execution object containing the event to process.
46
+ * @param {boolean} [doNotDecodeMessage] - Optional flag indicating whether to decode the message.
47
+ * @returns {Promise<Response<ResponseErrorType> | null | SQSBatchResponse>} - A promise that resolves to the response object, or null if no response is available.
48
+ * @throws {Error} - Throws an error if the response code is not within the range of 200 to 299 and failure is not allowed.
49
+ */
50
+ processEvent(execution: EventProcessorExecution<ResponseInnerType>, doNotDecodeMessage?: boolean): Promise<Response<ResponseErrorType | null> | null | SQSBatchResponse>;
51
+ /**
52
+ * Processes a raw event by executing the provided execution function and handling any errors or failures.
53
+ * @param {EventProcessorExecution<ResponseInnerType>} execution - The execution function to process the event.
54
+ * @param {boolean} doNotDecodeMessage - Flag indicating whether to decode the message or not.
55
+ * @returns {Promise<Response<ResponseErrorType> | null | SQSBatchResponse>} - A promise that resolves to a response object, null, or a SQS batch response.
56
+ */
57
+ private processRawEvent;
58
+ }
@@ -0,0 +1,101 @@
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 Transaction from './Transaction.js';
11
+ import Response from '../API/Response.js';
12
+ import Globals from '../Globals.js';
13
+ import Utils from '../Util/Utils.js';
14
+ /**
15
+ * EventProcessor class that processes events from an SQS queue.
16
+ * @template ResponseInnerType - The type of the inner response object.
17
+ */
18
+ export default class EventProcessor {
19
+ /**
20
+ * Constructs a new instance of the class.
21
+ * @param {SQSEvent} event - The event object representing the incoming SQS message.
22
+ * @param {Context} context - The context object representing the AWS Lambda execution context.
23
+ * @param {TransactionConfig} [config] - Optional configuration object for the transaction.
24
+ * @param {boolean} [allowFailure] - Optional flag indicating whether to allow failure for the transaction.
25
+ * @returns None
26
+ */
27
+ constructor(event, context, config, allowFailure) {
28
+ this.event = event;
29
+ this.context = context;
30
+ this.config = config || {};
31
+ this.allowFailure = !!allowFailure;
32
+ }
33
+ /**
34
+ * Processes an event using the provided execution object and returns a response.
35
+ * @param {EventProcessorExecution<ResponseInnerType>} execution - The execution object containing the event to process.
36
+ * @param {boolean} [doNotDecodeMessage] - Optional flag indicating whether to decode the message.
37
+ * @returns {Promise<Response<ResponseErrorType> | null | SQSBatchResponse>} - A promise that resolves to the response object, or null if no response is available.
38
+ * @throws {Error} - Throws an error if the response code is not within the range of 200 to 299 and failure is not allowed.
39
+ */
40
+ processEvent(execution, doNotDecodeMessage) {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ const resp = yield this.processRawEvent(execution, !!doNotDecodeMessage);
43
+ if (!this.allowFailure &&
44
+ resp &&
45
+ resp instanceof Response &&
46
+ !(resp.getCode() >= 200 && resp.getCode() < 300))
47
+ throw new Error(JSON.stringify(resp.getBody() || {}));
48
+ else if (resp)
49
+ return resp;
50
+ return null;
51
+ });
52
+ }
53
+ /**
54
+ * Processes a raw event by executing the provided execution function and handling any errors or failures.
55
+ * @param {EventProcessorExecution<ResponseInnerType>} execution - The execution function to process the event.
56
+ * @param {boolean} doNotDecodeMessage - Flag indicating whether to decode the message or not.
57
+ * @returns {Promise<Response<ResponseErrorType> | null | SQSBatchResponse>} - A promise that resolves to a response object, null, or a SQS batch response.
58
+ */
59
+ processRawEvent(execution, doNotDecodeMessage) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ var _a;
62
+ // safe check for empty events?
63
+ if (this.event.Records && this.event.Records.length > 0) {
64
+ // Regular cleanup of tmp disk to avoid tmp overflow on reused lambdas
65
+ if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.skipCleanTmp))
66
+ yield Utils.cleanTemporaryFolder();
67
+ // init transaction for all records
68
+ return yield new Transaction(this.event, this.context, Object.assign(Object.assign({}, this.config), { syncReturn: true })).execute((transaction) => __awaiter(this, void 0, void 0, function* () {
69
+ // Map records with decoded message when required
70
+ const decodedRecords = this.event.Records.map(eventRecord => doNotDecodeMessage ? eventRecord.body : JSON.parse(eventRecord.body));
71
+ // for each available event
72
+ const failureIDs = [];
73
+ for (const eventRecordIdx in decodedRecords) {
74
+ const eventRecord = decodedRecords[eventRecordIdx];
75
+ const message = this.event.Records[eventRecordIdx];
76
+ // Call execution
77
+ const resp = yield execution(transaction, eventRecord);
78
+ // check for failure
79
+ if (!resp ||
80
+ (resp instanceof Response && !((resp === null || resp === void 0 ? void 0 : resp.getCode()) >= 200 && (resp === null || resp === void 0 ? void 0 : resp.getCode()) < 300))) {
81
+ // response with failures or fail hard at first
82
+ if (this.allowFailure)
83
+ failureIDs.push(message.messageId);
84
+ else
85
+ return resp;
86
+ }
87
+ }
88
+ // not errored and loop ended - succeeded (might have failures)
89
+ if (this.allowFailure)
90
+ return {
91
+ batchItemFailures: failureIDs.map(id => ({ itemIdentifier: id })),
92
+ };
93
+ return Response.SuccessResponse(null);
94
+ }));
95
+ }
96
+ else
97
+ return Response.BadRequestResponse(Globals.ErrorResponseNoRecords, Globals.ErrorCode_NoRecords); // no event to be processed?
98
+ });
99
+ }
100
+ }
101
+ //# sourceMappingURL=EventProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EventProcessor.js","sourceRoot":"","sources":["../../../src/BaseEvent/EventProcessor.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,WAAkC,MAAM,kBAAkB,CAAA;AACjE,OAAO,QAA+B,MAAM,oBAAoB,CAAA;AAChE,OAAO,OAAO,MAAM,eAAe,CAAA;AACnC,OAAO,KAAK,MAAM,kBAAkB,CAAA;AAapC;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,cAAc;IAoBjC;;;;;;;OAOG;IACH,YACE,KAAe,EACf,OAAgB,EAChB,MAA0B,EAC1B,YAAsB;QAEtB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,EAAE,CAAA;QAC1B,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC,YAAY,CAAA;IACpC,CAAC;IAED;;;;;;OAMG;IACU,YAAY,CACvB,SAAqD,EACrD,kBAA4B;;YAE5B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,SAAS,EA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AM,cAAc,IAAI,cAAc,EAAE,CAAC;wBAC5C,MAAM,WAAW,GAAG,cAAc,CAAC,cAAc,CAAC,CAAA;wBAClD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,CAAA;wBAClD,iBAAiB;wBACjB,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,WAAW,EAAE,WAAW,CAAC,CAAA;wBACtD,oBAAoB;wBACpB,IACE,CAAC,IAAI;4BACL,CAAC,IAAI,YAAY,QAAQ,IAAI,CAAC,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAE,KAAI,GAAG,IAAI,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAE,IAAG,GAAG,CAAC,CAAC,EAChF,CAAC;4BACD,+CAA+C;4BAC/C,IAAI,IAAI,CAAC,YAAY;gCAAE,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;;gCACpD,OAAO,IAAI,CAAA;wBAClB,CAAC;oBACH,CAAC;oBACD,+DAA+D;oBAC/D,IAAI,IAAI,CAAC,YAAY;wBACnB,OAAO;4BACL,iBAAiB,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC,CAAC;yBAClE,CAAA;oBACH,OAAO,QAAQ,CAAC,eAAe,CAAC,IAAI,CAAC,CAAA;gBACvC,CAAC,CAAA,CAAC,CAAA;YACJ,CAAC;;gBACC,OAAO,QAAQ,CAAC,kBAAkB,CAChC,OAAO,CAAC,sBAAsB,EAC9B,OAAO,CAAC,mBAAmB,CAC5B,CAAA,CAAC,4BAA4B;QAClC,CAAC;KAAA;CACF"}
@@ -0,0 +1,50 @@
1
+ import { TransactionConfig } from './Transaction.js';
2
+ import Logger from '../Logger/Logger.js';
3
+ import Publisher from '../Publisher/Publisher.js';
4
+ /**
5
+ * A type that represents a modified version of the TransactionConfig type, excluding the 'throwOnErrors' and 'syncReturn' properties.
6
+ */
7
+ export type ProcessConfig = Omit<TransactionConfig, 'throwOnErrors' | 'syncReturn'>;
8
+ /**
9
+ * Represents a long-running process that executes a given function at a specified interval.
10
+ */
11
+ export default class Process {
12
+ /**
13
+ * Private member variable representing the interval value.
14
+ * @type {number}
15
+ * @private
16
+ */
17
+ private interval;
18
+ /**
19
+ * A logger object used for logging messages, errors, and other information.
20
+ * @readonly
21
+ */
22
+ readonly logger: Logger;
23
+ /**
24
+ * The publisher of the content.
25
+ */
26
+ readonly publisher: Publisher;
27
+ /**
28
+ * A reference to the NodeJS.Timeout object representing the interval timer.
29
+ */
30
+ timeout: NodeJS.Timeout;
31
+ /**
32
+ * Constructs a new instance of the LongRunningProcess class.
33
+ * @param {ProcessConfig} config - The configuration object for the process.
34
+ * @param {number} interval - The interval at which the process should run.
35
+ * @returns None
36
+ */
37
+ constructor(config: ProcessConfig, interval: number);
38
+ /**
39
+ * Executes the provided execution function at a specified interval.
40
+ * @param {Function} executionFunc - The function to execute.
41
+ * @returns None
42
+ */
43
+ execute(executionFunc: any): Promise<void>;
44
+ /**
45
+ * Executes the given execution function asynchronously and handles any exceptions that occur.
46
+ * @param {Function} executionFunc - The function to execute.
47
+ * @returns {boolean} - Returns true if the execution failed, false otherwise.
48
+ */
49
+ private iexecute;
50
+ }