@ikonintegration/ikapi 2.5.4 → 2.6.0-beta

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ikonintegration/ikapi",
3
- "version": "2.5.4",
3
+ "version": "2.6.0-beta",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "module": "main.js",
@@ -10,20 +10,21 @@
10
10
  "author": "",
11
11
  "license": "ISC",
12
12
  "dependencies": {
13
- "@aws/dynamodb-auto-marshaller": "0.7.1",
14
- "abind": "1.0.5",
15
- "aws-sdk": "^2.951.0",
16
- "bluebird": "3.7.2",
17
- "email-templates": "^8.0.7",
18
- "esm": "3.2.25",
19
- "is-email": "^1.0.1",
20
- "is-uuid": "1.0.2",
21
- "json-stringify-safe": "5.0.1",
22
- "ksuid": "2.0.0",
23
- "libphonenumber-js": "^1.9.22",
24
- "nodemailer": "^6.6.3",
25
- "path-to-regexp": "6.2.0",
26
- "pg": "^8.6.0",
13
+ "@aws/dynamodb-auto-marshaller": "^0.7.1",
14
+ "abind": "^1.0.5",
15
+ "aws-sdk": "^2.1034.0",
16
+ "bluebird": "^3.7.2",
17
+ "email-templates": "^8.0.8",
18
+ "esm": "^3.2.25",
19
+ "is-email": "^1.0.2",
20
+ "is-uuid": "^1.0.2",
21
+ "json-stringify-safe": "^5.0.1",
22
+ "ksuid": "^3.0.0",
23
+ "libphonenumber-js": "^1.9.43",
24
+ "nodemailer": "^6.7.1",
25
+ "path-to-regexp": "^6.2.0",
26
+ "pg": "^8.7.1",
27
+ "sha1": "^1.1.1",
27
28
  "stack-trace": "0.0.10",
28
29
  "superstruct": "0.8.4"
29
30
  }
@@ -5,9 +5,11 @@ export default class IKResponse {
5
5
  this._statusCode = statusCode;
6
6
  this._body = body;
7
7
  //
8
- this._streamingOut = false;
9
- this._isStream = false;
8
+ this._streamingOut = false; //internal -- flag to indicate streaming out has started and avoid double stream call
9
+ //indeally it should be moved to initialization method as we dont' want them to be changed on the go and also give the false impression of getters with the current naming pattern
10
+ this._isStream = false; //
10
11
  this._contextRawBody = false;
12
+ this._throwOnErrors = false;
11
13
  //
12
14
  this._headers = {
13
15
  "Access-Control-Allow-Origin": "*",
@@ -19,7 +21,7 @@ export default class IKResponse {
19
21
  getBody() { return this._body; }
20
22
  appendIntoBody(key, value) { this._body[key] = value; }
21
23
  appendHeader(key, value) { this._headers[key] = value; }
22
- build(context, requestID, onQueue, transaction) {
24
+ build(context, requestID, isBatch, transaction) {
23
25
  //Stream support
24
26
  if (this._streamingOut) return;
25
27
  if (this._isStream) return this._pipe(context, requestID);
@@ -36,7 +38,7 @@ export default class IKResponse {
36
38
  };
37
39
  //log response and respond to context
38
40
  transaction.logger.debug(b)
39
- if (!onQueue) context.succeed(b);
41
+ if (!isBatch) context.succeed(b);
40
42
  }
41
43
  _pipe(context, requestID) {
42
44
  //Check if not streaming
@@ -60,11 +62,12 @@ export default class IKResponse {
60
62
  //
61
63
  function CustomError(body) {
62
64
  this.name = body && body.error ? body.error : 'UnknownError';
63
- this.message = body;
65
+ this.message = body && body.message ? body.message : 'Unknown error!';
64
66
  }
65
67
  CustomError.prototype = new Error();
66
68
  //
67
- context.fail(new CustomError(this._body));
69
+ if (!this._throwOnErrors) context.fail(new CustomError(this._body));
70
+ else throw (new CustomError(this._body));
68
71
  }
69
72
  }
70
73
  }
@@ -108,5 +111,6 @@ export function IKSuccessStreamResponse(stream, contentType) {
108
111
  export function IKStepFunctionResponse(body, optionalCode) {
109
112
  const resp = new IKResponse(optionalCode || 200, body);
110
113
  resp._contextRawBody = true;
114
+ resp._throwOnErrors = true;
111
115
  return resp;
112
116
  }
@@ -16,14 +16,16 @@ import IKResponse, { IKBadRequestResponseWithRollback } from '../API/IKResponse'
16
16
 
17
17
  //
18
18
  export default class IKTransaction {
19
- constructor(event, context, config, _isQueue) {
19
+ constructor(event, context, config, _isBatch, _retrowErrors) {
20
20
  this._event = event;
21
21
  this._context = context;
22
22
  this._config = config;
23
23
  //queue support
24
- this._onQueue = _isQueue;
24
+ this._isBatch = _isBatch;
25
25
  this._resp = null;
26
26
  //
27
+ this._retrowErrors = _retrowErrors;
28
+ //
27
29
  this.logger = new IKLogger({/*COFIG S3/SQS HERE*/}, Utils.logLevel(), (context.awsRequestId ? context.awsRequestId : (event.requestContext ? event.requestContext.requestId : 'unknown')));
28
30
  this.request = new IKRequest(this._event, this._context, this);
29
31
  this.publisher = new IKPublisher(config.publisher);
@@ -39,7 +41,7 @@ export default class IKTransaction {
39
41
  return await this._execute(executionFunc);
40
42
  });
41
43
  });
42
- if (this._onQueue) return this._resp;
44
+ if (this._isBatch) return this._resp;
43
45
  }
44
46
  //Executions
45
47
  async _execute(executionFunc) {
@@ -50,19 +52,22 @@ export default class IKTransaction {
50
52
  this._resp = await executionFunc(this);
51
53
  //Answer client
52
54
  if (this._resp && this._resp instanceof IKResponse) {
53
- this._resp.build(this._context, this.request.getRequestID(), this._onQueue, this);
55
+ this._resp.build(this._context, this.request.getRequestID(), this._isBatch, this);
54
56
  executionFailed = !!(this._resp.getBody() && this._resp.getBody().rollback);
55
57
  } else {
56
58
  this._resp = this._getErrorResponse(IKGlobals.ErrorResponseInvalidServerResponse, IKGlobals.ErrorCode_APIError)
57
- this._resp.build(this._context, this.request.getRequestID(), this._onQueue, this);
59
+ this._resp.build(this._context, this.request.getRequestID(), this._isBatch, this);
58
60
  this.logger.error("Invalid response object from main request code.");
59
61
  }
60
62
  } catch (e) { /*EXECUTION FAIL*/
61
63
  this.logger.error('Exception when executing main request code.');
62
64
  this.logger.exception(e);
65
+ //retrow?
66
+ if (this._retrowErrors) throw e;
67
+ //envelope exception?
63
68
  if (executionFailed) {
64
69
  this._resp = this._getErrorResponse(IKGlobals.ErrorResponseUnhandledError, IKGlobals.ErrorCode_APIError);
65
- this._resp.build(this._context, this.request.getRequestID(), this._onQueue, this);
70
+ this._resp.build(this._context, this.request.getRequestID(), this._isBatch, this);
66
71
  }
67
72
  } return executionFailed;
68
73
  }
@@ -86,6 +91,8 @@ export default class IKTransaction {
86
91
  } catch (e) {
87
92
  this.logger.error('Exception when executing DB transactions.');
88
93
  this.logger.log(e);
94
+ //retrow?
95
+ if (this._retrowErrors) throw e;
89
96
  }
90
97
  }
91
98
  async _executeLoggerFlush(safeExecution) {
@@ -95,6 +102,8 @@ export default class IKTransaction {
95
102
  } catch (e) {
96
103
  this.logger.error('Exception when flushing logs.');
97
104
  this.logger.exception(e);
105
+ //retrow?
106
+ if (this._retrowErrors) throw e;
98
107
  } finally {
99
108
  this.logger.debug("Transaction ended");
100
109
  }
@@ -4,6 +4,9 @@ import Utils from "./../../API/IKUtils";
4
4
  //
5
5
  import IKGlobals from './../../IKGlobals';
6
6
  import IKDB from './../Prototype/IKDB';
7
+ //reusable connection
8
+ var DDB_CONN = null;
9
+ var DDB_CONN_HASH = null;
7
10
  //
8
11
  export default class IKDB_DDB extends IKDB {
9
12
  constructor(config, transaction) {
@@ -15,6 +18,10 @@ export default class IKDB_DDB extends IKDB {
15
18
  if (config && this.tableName) { localConsole.debug(`Using table: ${this.tableName} on region: ${this.region}`); }
16
19
  }
17
20
 
21
+ async _getConnection() {
22
+ if (!DDB_CONN && !DDB_CONN_HASH && DDB_CONN_HASH != sha1(this.region)) DDB_CONN = await this._newConnection(this.config);
23
+ return DDB_CONN;
24
+ }
18
25
  async connect() {
19
26
  const localConsole = (this.transaction ? this.transaction.logger : console);
20
27
  //setup db
@@ -29,6 +36,9 @@ export default class IKDB_DDB extends IKDB {
29
36
  //initialize connection
30
37
  AWS.config.update({httpOptions: sslAgent, region: this.region});
31
38
  this.connection = new AWS.DynamoDB();
39
+ //Reusable logic
40
+ DDB_CONN = this.connection;
41
+ DDB_CONN_HASH = sha1(this.region);
32
42
  }
33
43
  }
34
44
  }
@@ -17,7 +17,7 @@ export default class IKDynamoStream {
17
17
  async _processRawEvent(execution) {
18
18
  if (this.event.Records && this.event.Records.length > 0) { //safe check for empty events?
19
19
  //init transaction for all records
20
- return await (new IKTransaction(this.event, this.context, this.apiConfig, true /*on queue*/)).execute(async (transaction) => {
20
+ return await (new IKTransaction(this.event, this.context, this.apiConfig, true /*batch processing*/)).execute(async (transaction) => {
21
21
  //for each available event
22
22
  for (let eventRecord of this.event.Records) {
23
23
  //Prepare parsed record
@@ -17,7 +17,7 @@ export default class IKEventProcessor {
17
17
  async _processRawEvent(execution, doNotDecodeMessage) {
18
18
  if (this.event.Records && this.event.Records.length > 0) { //safe check for empty events?
19
19
  //init transaction for all records
20
- return await (new IKTransaction(this.event, this.context, this.apiConfig, true /*on queue*/)).execute(async (transaction) => {
20
+ return await (new IKTransaction(this.event, this.context, this.apiConfig, true /*batch processing*/)).execute(async (transaction) => {
21
21
  //Map records with decoded message when required
22
22
  const decodedRecords = this.event.Records.map((eventRecord) => (doNotDecodeMessage ? eventRecord.body : JSON.parse(eventRecord.body)));
23
23
  //If is batch, return execution
@@ -4,10 +4,11 @@ import { IKStepFunctionResponse } from './API/IKResponse';
4
4
  //
5
5
  export default class IKStepTransaction extends IKTransaction {
6
6
  constructor(event, context, config) {
7
- super(event, context, config, false);
7
+ super(event, context, config, false, true /* retrowErrors */);
8
8
  }
9
9
  /* Response support */
10
10
  _getErrorResponse(error, code) {
11
11
  return IKStepFunctionResponse({ err: error, errCode: code }, 400);
12
12
  }
13
13
  }
14
+
@@ -1,6 +1,9 @@
1
1
  import AWS from "aws-sdk";
2
2
  //
3
3
  import Utils from "./../API/IKUtils";
4
+ //reusable client
5
+ var PUBLISHER_CONN = null;
6
+ var PUBLISHER_CONN_HASH = null;
4
7
  //
5
8
  export default class IKPublisher {
6
9
  constructor(config) {
@@ -9,25 +12,33 @@ export default class IKPublisher {
9
12
  console.debug(`Using region: ${this.region}`);
10
13
  }
11
14
  }
12
-
15
+ /* Public */
13
16
  async publishOnTopic(messageObject, topic, additionalProps) {
14
17
  let resp = null;
15
18
  try {
16
- //Configure when sending!
17
- let configObj = { region: this.region };
18
- if (Utils.isOffline()) configObj = { ...configObj, accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY };
19
- AWS.config.update(configObj);
19
+ this._connect();
20
20
  //Send to SNS
21
21
  const params = {
22
22
  Message: JSON.stringify(messageObject),
23
23
  TopicArn: topic,
24
24
  ...(additionalProps ? additionalProps : {}),
25
25
  };
26
- resp = await (new AWS.SNS({ apiVersion: '2010-03-31' })).publish(params).promise();
26
+ resp = await PUBLISHER_CONN.publish(params).promise();
27
27
  } catch (e) {
28
28
  console.error(`Error while publishing into topic ${topic} with error: ${e}`);
29
29
  }
30
30
  console.debug('Publisher resp', resp);
31
31
  return resp;
32
32
  }
33
+ /* Private */
34
+ _connect() {
35
+ if (!PUBLISHER_CONN && !PUBLISHER_CONN_HASH && PUBLISHER_CONN_HASH != sha1(this.regiond)) {
36
+ //Configure when sending!
37
+ let configObj = { region: this.region };
38
+ if (Utils.isOffline()) configObj = { ...configObj, accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY };
39
+ AWS.config.update(configObj);
40
+ PUBLISHER_CONN = (new AWS.SNS({ apiVersion: '2010-03-31' }));
41
+ PUBLISHER_CONN_HASH = sha1(this.region);
42
+ }
43
+ }
33
44
  }