@izara_project/izara-market-library-service-schemas 1.0.17 → 1.0.18

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 (35) hide show
  1. package/package.json +4 -4
  2. package/src/GenerateCodeLibs/src/GenerateCodeLibs.js +24 -0
  3. package/src/TemplateManager/src/FindData/FindDataYaml/data.js +0 -9
  4. package/src/TemplateManager/src/GenerateCode.js +16 -5
  5. package/src/TemplateManager/src/OutPerActionComplete/OutUpdateComplete/mainFunction/template.ejs +1 -1
  6. package/src/TemplateManager/src/PerActionEndpoint/Handler/HdrDsq/template.ejs +2 -2
  7. package/src/TemplateManager/src/PerActionEndpoint/Handler/HdrSqs/template.ejs +2 -2
  8. package/src/TemplateManager/src/PerActionEndpoint/MainFunction/Create/template.ejs +41 -29
  9. package/src/TemplateManager/src/PerActionEndpoint/MainFunction/Update/template.ejs +28 -0
  10. package/src/TemplateManager/src/RelationshipPerAction/CreateRelationship/createRelationshipComplete/mainFunction/template.ejs +1 -1
  11. package/src/TemplateManager/src/RelationshipPerAction/DeleteRelationship/DeleteRelationshipComplete/mainFunction/template.ejs +1 -1
  12. package/src/TemplateManager/src/RelationshipPerAction/UpdateRelationshipSchema/updateRalationshipComplete/mainFunction/template.ejs +1 -1
  13. package/src/TemplateManager/src/ResourceYaml/dynamodb/defaultDynamoDbTable.js +15 -0
  14. package/src/TemplateManager/src/externalService/LambdaRole/data.js +7 -20
  15. package/src/TemplateManager/src/externalService/SnsTopicSubscriotions/data.js +1 -1
  16. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/functionYaml/data.js +100 -0
  17. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/functionYaml/template.ejs +27 -0
  18. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/handler/data.js +58 -0
  19. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/handler/template.ejs +103 -0
  20. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/mainFunction/data.js +56 -0
  21. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/mainFunction/template.ejs +180 -0
  22. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/sns-sqs/data.js +70 -0
  23. package/src/TemplateManager/src/flowTag/webSocket/webSocketComplete/sns-sqs/template.ejs +43 -0
  24. package/src/TemplateManager/src/flowTag/webSocket/webSocketConnect/functionYaml/data.js +22 -5
  25. package/src/TemplateManager/src/flowTag/webSocket/webSocketConnect/functionYaml/template.ejs +22 -3
  26. package/src/TemplateManager/src/flowTag/webSocket/webSocketConnect/handler/data.js +3 -3
  27. package/src/TemplateManager/src/flowTag/webSocket/webSocketConnect/handler/template.ejs +19 -14
  28. package/src/TemplateManager/src/flowTag/webSocket/websocketHandler/functionYaml/data.js +32 -8
  29. package/src/TemplateManager/src/flowTag/webSocket/websocketHandler/functionYaml/template.ejs +5 -7
  30. package/src/TemplateManager/src/flowTag/webSocket/websocketHandler/handler/data.js +59 -0
  31. package/src/TemplateManager/src/flowTag/webSocket/websocketHandler/handler/template.ejs +130 -0
  32. package/src/TemplateManager/src/flowTag/webSocket/websocketHandler/{lambda → mainFunction}/data.js +5 -3
  33. package/src/TemplateManager/src/flowTag/webSocket/websocketHandler/mainFunction/template.ejs +133 -0
  34. package/src/TemplateManager/src/libs/Consts.js +5 -2
  35. package/src/TemplateManager/src/flowTag/webSocket/websocketHandler/lambda/template.ejs +0 -131
@@ -22,7 +22,7 @@ const fs = require('fs');
22
22
  const { ACTIONS, HANDLER } = require('@izara_project/izara-core-library-service-schemas/src/Consts')
23
23
 
24
24
  const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase, firstLetterUpperCase, checkOverWriteGenerateMainFunction } = require("../../../../../../MainLibs/src/Utils")
25
- const { DEFAULT_HANDLER_PER_ACTION, SOURCE_PATH, defaultIamRolePerAction, createIamRole, RESOURCE_CLASSES, SNS_RESOURCE, resourceNames } = require("../../../../libs/Consts");
25
+ const { DEFAULT_HANDLER_PER_ACTION, SOURCE_PATH, defaultIamRolePerAction, createIamRole, RESOURCE_CLASSES, SNS_RESOURCE, resourceNames, DYNAMO_RESOURCE, SAVE_FILE_NAME } = require("../../../../libs/Consts");
26
26
 
27
27
  const templatePath = path.join(__dirname, "template.ejs")
28
28
 
@@ -39,10 +39,10 @@ function data(_izContext, srcPath) {
39
39
  }
40
40
 
41
41
  function createSourceParams(_izContext, srcPath) {
42
- let functionName = "FlowSchemaInvoke"
43
- let additionalResourcePermission = defaultIamRolePerAction();
42
+ let functionName = "FlowSchema"
44
43
  let handlerType = upperCase("hdrWbs")
45
- let functionNameConfig = functionName + handlerType
44
+ let additionalResourcePermission = defaultIamRolePerAction();
45
+ let route = "webSocket"
46
46
  additionalResourcePermission.push(
47
47
  createIamRole(
48
48
  {
@@ -53,20 +53,44 @@ function createSourceParams(_izContext, srcPath) {
53
53
  [
54
54
  resourceNames(RESOURCE_CLASSES.sns, "*")
55
55
  ]
56
+ ),
57
+ createIamRole(
58
+ {
59
+ [RESOURCE_CLASSES.dynamoDbTable]: [
60
+ DYNAMO_RESOURCE.putItem,
61
+ DYNAMO_RESOURCE.getItem,
62
+ DYNAMO_RESOURCE.query,
63
+ DYNAMO_RESOURCE.deleteItem,
64
+ DYNAMO_RESOURCE.updateItem
65
+ ]
66
+ },
67
+ [
68
+ resourceNames(RESOURCE_CLASSES.dynamoDbTable, "WebSocketTask")
69
+ ]
70
+ ),
71
+ createIamRole(
72
+ {
73
+ "execute-api": [
74
+ "ManageConnections"
75
+ ]
76
+ },
77
+ [
78
+ resourceNames(RESOURCE_CLASSES.webSocket)
79
+ ]
56
80
  )
57
81
  )
58
82
  return {
59
83
  templatePath: templatePath,
60
84
  templateData: {
61
- resourceLocation: SOURCE_PATH.resourceLocationPerAction,
85
+ resourceLocation: SOURCE_PATH.resourceLocationWebSocket,
62
86
  functionName,
63
87
  handlerType,
64
- functionNameConfig,
65
- additionalResourcePermission
88
+ additionalResourcePermission,
89
+ route
66
90
  },
67
91
  setting: {
68
92
  savePath: path.join(srcPath, SOURCE_PATH.appYaml),
69
- saveFileName: "FlowSchemaInvoke",
93
+ saveFileName: SAVE_FILE_NAME.flowSchema,
70
94
  fileExtension: ".yml",
71
95
  isAppend: true
72
96
  }
@@ -1,14 +1,12 @@
1
1
  <%_ const join = require('path').join; _%>
2
- <%- firstLetterUpperCase(functionNameConfig) %>:
2
+ <%- firstLetterUpperCase(functionName) %><%- handlerType -%>:
3
3
  handler: <%- join(resourceLocation, `${firstLetterUpperCase(functionName)}_${firstLetterUpperCase(handlerType)}.main`)%>
4
4
  name: ${self:custom.iz_resourcePrefix}<%- firstLetterUpperCase(functionName) %>
5
5
  events:
6
- - sqs:
7
- arn: arn:aws:sqs:${self:custom.iz_region}:${self:custom.iz_accountId}:${self:custom.iz_resourcePrefix}<%- firstLetterUpperCase(functionName) %>
8
- batchSize: 10
9
- filterPatterns: #**** need to update serverless framwork upper v.2.69.1
10
- - body: {"MessageAttributes":{"callingFlow":{"Value":["${self:custom.iz_resourcePrefix}<%-firstLetterUpperCase(functionName) %>"]}}} # functionName of callingFlow
11
- - body: {"MessageAttributes":{"callingFlow":{"Value":[{"exists":false}]}}}
6
+ - websocket:
7
+ route: <%- route %>
8
+ # authorizer: ${self:custom.iz_authorizerAppLevel}
9
+ # identifierResource: 'route.request.header.Auth'
12
10
  iamRoleStatements:
13
11
  <%_ additionalResourcePermission.forEach(resourcePermission => { _%>
14
12
  - Effect: <%- resourcePermission.effect %>
@@ -0,0 +1,59 @@
1
+ /*
2
+ Copyright (C) 2020 Sven Mason <http://izara.io>
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ 'use strict';
19
+ const path = require('path');
20
+ const fs = require('fs');
21
+
22
+ const { ACTIONS, HANDLER } = require('@izara_project/izara-core-library-service-schemas/src/Consts')
23
+
24
+ const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase, firstLetterUpperCase } = require("../../../../../../MainLibs/src/Utils")
25
+ const { DEFAULT_HANDLER_PER_ACTION, SOURCE_PATH } = require("../../../../libs/Consts");
26
+
27
+ const templatePath = path.join(__dirname, "template.ejs")
28
+
29
+ /**
30
+ * receive objectSchema
31
+ * create data for WebScoket handler template
32
+ *
33
+ * @param {Object} objectSchema
34
+ * @return {{templatePath, templateData,setting}}
35
+ */
36
+
37
+
38
+ function data(_izContext, srcPath) {
39
+
40
+ return [createParamsForCreateSource(_izContext, srcPath)]
41
+
42
+
43
+ }
44
+
45
+ function createParamsForCreateSource(_izContext, srcPath) {
46
+ let functionName = "FlowSchema"
47
+ let handlerType = "HdrWbs"
48
+ return {
49
+ templatePath: templatePath,
50
+ templateData: {},
51
+ setting: {
52
+ savePath: path.join(srcPath, SOURCE_PATH.webSocket),
53
+ saveFileName: `${functionName}_${handlerType}`,
54
+ fileExtension: ".js",
55
+ isAppend: false
56
+ }
57
+ }
58
+ }
59
+ module.exports = data
@@ -0,0 +1,130 @@
1
+ /*
2
+ Copyright (C) 2021 Sven Mason <http://izara.io>
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ */
17
+
18
+ 'use strict';
19
+
20
+ const izara = require("@izara_project/izara-middleware");
21
+ const middleware = izara.middlewareHandler;
22
+ // const AWS = require('aws-sdk');
23
+ // const api = new AWS.ApiGatewayManagementApi({ endpoint: process.env.iz_webSocketEndpoint });
24
+ const izaraShared = require('@izara_project/izara-shared')
25
+ const dynamodbSharedLib = izaraShared.dynamodbSharedLib
26
+ const callingFlowSharedLib = izaraShared.callingFlowSharedLib;
27
+ const hash = require('object-hash')
28
+
29
+ const { ApiGatewayManagementApiClient, PostToConnectionCommand } = require("@aws-sdk/client-apigatewaymanagementapi");
30
+ const flowSchema = require('./FlowSchema_Main');
31
+
32
+ const client = new ApiGatewayManagementApiClient({
33
+ endpoint: `https://${process.env.iz_webSocketEndpoint}`
34
+ })
35
+ module.exports.main = middleware.wrap(async (event, context, callback) => {
36
+
37
+ event._izContext.logger.debug('Event:', event);
38
+
39
+ try {
40
+
41
+ let eventParams = JSON.parse(event.body)
42
+
43
+ if (event.requestContext) {
44
+ const route = event.requestContext.routeKey;
45
+ const connectionId = event.requestContext.connectionId;
46
+
47
+ switch (route) {
48
+ case null:
49
+ console.log('Received unknown route:', route)
50
+ break
51
+ case 'webSocket':
52
+ console.log("event in route", event)
53
+ let callingFlow = eventParams?.callingFlow ? eventParams.callingFlow : {}
54
+ console.log("eventParams::", eventParams)
55
+ await flowSchema.flowSchema(
56
+ event._izContext,
57
+ eventParams,
58
+ //(<additionalParams>)
59
+ //(</additionalParams>)
60
+ callingFlowSharedLib.addCallingFlowToPassOnProperties(callingFlow)
61
+ )
62
+
63
+ // if (returnValueFlowSchema) {
64
+ await dynamodbSharedLib.putItem(
65
+ event._izContext,
66
+ await dynamodbSharedLib.tableName(event._izContext, "WebSocketTask"),
67
+ {
68
+ taskKey: "uploadS3Data" + hash(connectionId),
69
+ connectionId: connectionId,
70
+ }
71
+ )
72
+ // }
73
+
74
+ console.log({ message: eventParams })
75
+ // await postMessage(returnValueFlowSchema, connectionId)
76
+ // await postToConnection({ message: eventParams }, connectionId)
77
+ break
78
+ }
79
+ } else {
80
+ const connId = event.connId;
81
+ // await postMessage({ message: event.message }, connId);
82
+ await postToConnection({ message: event.message }, connId);
83
+ }
84
+
85
+ return (izara.response.webSocketSuccess());
86
+
87
+ } catch (err) {
88
+ const connId = event.requestContext.connectionId
89
+ event._izContext.logger.error('Error, WebSocket: ', err);
90
+ // await sendErrorMessage({ message: err.message }, connId);
91
+ await postToConnection({ message: err.message }, connId);
92
+ return (izara.response.failure(err));
93
+ }
94
+ });
95
+
96
+ async function postMessage(data, connectionId) {
97
+ const params = {
98
+ ConnectionId: connectionId,
99
+ Data: JSON.stringify(data),
100
+ }
101
+ return api.postToConnection(params).promise();
102
+ };
103
+
104
+ async function sendErrorMessage(errorMessage, connectionId) {
105
+ const params = {
106
+ ConnectionId: connectionId,
107
+ Data: JSON.stringify(errorMessage)
108
+ }
109
+ return api.postToConnection(params).promise();
110
+ }
111
+
112
+ const postToConnection = async (message, connectionId) => {
113
+ try {
114
+ const messageParams = JSON.stringify(message)
115
+ const command = new PostToConnectionCommand({
116
+ ConnectionId: connectionId,
117
+ Data: Buffer.from(messageParams)
118
+ })
119
+ // console.log("command::", command)
120
+ // console.log("client::", client)
121
+ await client.send(command);
122
+ console.log(`send Message: ${JSON.stringify(message)} to ${connectionId} 1`)
123
+ } catch (err) {
124
+ if (err.name === "GoneException") {
125
+ console.log(`message send to connectionIds ${connectionId} is no longer connect`)
126
+ } else {
127
+ console.error(`Error post message: ${err}`)
128
+ }
129
+ }
130
+ }
@@ -21,7 +21,7 @@ const fs = require('fs');
21
21
 
22
22
  const { ACTIONS, HANDLER } = require('@izara_project/izara-core-library-service-schemas/src/Consts')
23
23
 
24
- const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase, firstLetterUpperCase, checkOverWriteGenerateMainFunction } = require("../../../../../../MainLibs/src/Utils")
24
+ const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase, firstLetterUpperCase } = require("../../../../../../MainLibs/src/Utils")
25
25
  const { DEFAULT_HANDLER_PER_ACTION, SOURCE_PATH } = require("../../../../libs/Consts");
26
26
 
27
27
  const templatePath = path.join(__dirname, "template.ejs")
@@ -43,12 +43,14 @@ function data(_izContext, srcPath) {
43
43
  }
44
44
 
45
45
  function createParamsForCreateSource(_izContext, srcPath) {
46
+ let functionName = "FlowSchema"
47
+
46
48
  return {
47
49
  templatePath: templatePath,
48
50
  templateData: {},
49
51
  setting: {
50
- savePath: path.join(srcPath, SOURCE_PATH.lambdaPerAction),
51
- saveFileName: "FlowSchemaInvoke",
52
+ savePath: path.join(srcPath, SOURCE_PATH.webSocket),
53
+ saveFileName: `${functionName}_Main`,
52
54
  fileExtension: ".js",
53
55
  isAppend: false
54
56
  }
@@ -0,0 +1,133 @@
1
+ /*
2
+ Copyright (C) 2020 Sven Mason <http: //izara.io>
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see
16
+ <http: //www.gnu.org/licenses />.
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ const hash = require("object-hash");
22
+ const getObjectSchema = require('@izara_project/izara-core-library-service-schemas/src/GetObjectSchema');
23
+
24
+ const izaraShared = require('@izara_project/izara-shared');
25
+ const dynamodbSharedLib = izaraShared.dynamodbSharedLib;
26
+ const snsSharedLib = izaraShared.snsSharedLib;
27
+ const asyncFlowSharedLib = izaraShared.asyncFlowSharedLib;
28
+ const callingFlowSharedLib = izaraShared.callingFlowSharedLib;
29
+ const lambdaSharedLib = izaraShared.lambdaSharedLib
30
+
31
+ const externalRequest = require('@izara_project/izara-core-library-external-request');
32
+ const sns = externalRequest.sns
33
+
34
+ const utils = require('@izara_project/izara-market-library-service-schemas/src/MainLibs/src/Utils')
35
+ const NoRetryError = require('@izara_project/izara-core-library-core').NoRetryError
36
+ const { v4: uuidv4 } = require('uuid')
37
+ const coreConsts = require("@izara_project/izara-core-library-core/src/Consts");
38
+ const { TOPIC_NAME_GENERATE_CODE } = require('@izara_project/izara-market-library-service-schemas/src/GenerateCodeLibs/src/Consts')
39
+ /**
40
+ *
41
+ *
42
+ * description of function.
43
+ * @param {Object} _izContext
44
+ * @param {CorrelationIds} _izContext.correlationIds - property of _izContext
45
+ * @param {Logger} _izContext.logger - property of _izContext
46
+ * @param {Object} requestParams - request params
47
+ * @param {Object} requestParams.identifiers - identifiers for get data
48
+ * @param {Object} requestParams.additionalRequest - additionalRequest
49
+ *
50
+ *
51
+ * @returns {object} description of return value
52
+ */
53
+
54
+ module.exports.flowSchema = async (
55
+ _izContext,
56
+ requestParams,
57
+ callingFlowConfig = {},
58
+ //(<additionalParams>)
59
+ //(</additionalParams>)
60
+ ) => {
61
+
62
+ try {
63
+ _izContext.logger.debug("WebSocketInvoke _izContext", _izContext)
64
+ _izContext.logger.debug("WebSocketInvoke requestParams", requestParams)
65
+ _izContext.logger.debug("WebSocketInvoke callingFlowConfig", callingFlowConfig)
66
+
67
+ _izContext.correlationIds.set(coreConsts.BASE_USER_ID, "BasDev");
68
+ _izContext.correlationIds.set(coreConsts.RESOURCE_USE_USER_ID, "BasDevTarget");
69
+
70
+ let flowSchema = await getObjectSchema.getFlowSchemaS3WithCache(_izContext, {
71
+ flowTag: requestParams.flowTag,
72
+ serviceTag: process.env.iz_serviceTag
73
+ // serviceTag: "GenerateCodeTamplateBas002"
74
+ })
75
+
76
+ _izContext.logger.debug("getFlowSchema", flowSchema)
77
+
78
+
79
+ if (!flowSchema) {
80
+ throw new NoRetryError(`flowTag not found ${requestParams.flowTag}`)
81
+ }
82
+
83
+ if (flowSchema.uploadS3 === true) {
84
+ if (!flowSchema.hasOwnProperty("objType")) {
85
+ throw new NoRetryError(`flowTag has uploadS3 setting should have objType in flowSchema`)
86
+ }
87
+ };
88
+
89
+ // get objectType
90
+ let objectSchema = await getObjectSchema.getObjSchemaS3WithHierarchy(_izContext, flowSchema.objType)
91
+ _izContext.logger.debug("objectSchema in flowShcema mainFunction", objectSchema)
92
+
93
+ _izContext.correlationIds.get(coreConsts.X_CORRELATION_ID)
94
+
95
+ // create message Object to create Endpoint
96
+ let messageObject = {
97
+ fieldNames: {
98
+ userId: _izContext.correlationIds.get(coreConsts.BASE_USER_ID),
99
+ // userId: "mockUserId",
100
+ submittedByUserId: _izContext.correlationIds.get(coreConsts.RESOURCE_USE_USER_ID),
101
+ // submittedByUserId: "mockSubmittedByUserId",
102
+ startTime: Date.now(),
103
+ importConfigId: requestParams.importConfigId,
104
+ importBatchStatus: "process",
105
+ importType: requestParams.importType,
106
+ fileName: requestParams.fileName,
107
+ fileSize: requestParams.fileSize
108
+ }
109
+ }
110
+ // create callingFlow
111
+ messageObject = callingFlowSharedLib.addCallingFlowToSnsRequestMessageObject(
112
+ messageObject,
113
+ callingFlowSharedLib.addParentCallingFlowConfig(
114
+ callingFlowConfig,
115
+ callingFlowSharedLib.createCallingFlowConfig(
116
+ await lambdaSharedLib.lambdaFunctionName(_izContext, TOPIC_NAME_GENERATE_CODE.createNodeComplete), {}
117
+ )
118
+ )
119
+ )
120
+
121
+ // send message to ImportBatchCreateHdrSqs
122
+ let sendMessageToCreateEndpoint = {
123
+ Message: JSON.stringify(messageObject),
124
+ TopicArn: await snsSharedLib.snsTopicArn(_izContext, `In${utils.firstLetterUpperCase(objectSchema.objectType)}Create`)
125
+ }
126
+ _izContext.logger.debug("sendMessageToCreateEndpoint", sendMessageToCreateEndpoint);
127
+ await sns.publishAsync(_izContext, sendMessageToCreateEndpoint);
128
+
129
+ } catch (err) {
130
+ _izContext.logger.error('error WebSocketInvoke: ', err)
131
+ throw (err)
132
+ }
133
+ }
@@ -101,7 +101,9 @@ const SOURCE_PATH = {
101
101
  resourceLocationFindData: 'src/generatedCode/FindData/source',
102
102
  resourceLocationRelationshipPerAction: 'src/generatedCode/RelationshipPerAction/source/',
103
103
  resourceLocationTranslateId: 'src/generatedCode/TranslateId/source/',
104
- resourceLocationProcessLogical: "src/generatedCode/ProcessLogical/source/"
104
+ resourceLocationProcessLogical: "src/generatedCode/ProcessLogical/source/",
105
+ webSocket: "../src/generatedCode/WebSocket/source/",
106
+ resourceLocationWebSocket: "src/generatedCode/WebSocket/source/"
105
107
  };
106
108
 
107
109
 
@@ -172,7 +174,8 @@ const SAVE_FILE_NAME = {
172
174
  snsSubscription: "generatedSnsServiceConfig",
173
175
  translateId: "TranslateIdsRequest",
174
176
  findData: "findData",
175
- processLogicalYaml: "processLogical"
177
+ processLogicalYaml: "processLogical",
178
+ flowSchema: "flowSchema"
176
179
  }
177
180
 
178
181
  const FUNCTION_NAME = {
@@ -1,131 +0,0 @@
1
- /*
2
- Copyright (C) 2021 Sven Mason <http://izara.io>
3
-
4
- This program is free software: you can redistribute it and/or modify
5
- it under the terms of the GNU Affero General Public License as
6
- published by the Free Software Foundation, either version 3 of the
7
- License, or (at your option) any later version.
8
-
9
- This program is distributed in the hope that it will be useful,
10
- but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- GNU Affero General Public License for more details.
13
-
14
- You should have received a copy of the GNU Affero General Public License
15
- along with this program. If not, see <http://www.gnu.org/licenses/>.
16
- */
17
-
18
- 'use strict';
19
-
20
- const izara = require("@izara_project/izara-middleware");
21
- const middleware = izara.middlewareHandler;
22
- const AWS = require('aws-sdk');
23
- const api = new AWS.ApiGatewayManagementApi({ endpoint: process.env.iz_webSocketEndpoint });
24
- const izaraShared = require('@izara_project/izara-shared')
25
- const dynamodbSharedLib = izaraShared.dynamodbSharedLib
26
- const sqsSharedLib = izaraShared.sqsSharedLib;
27
- const snsSharedLib = izaraShared.snsSharedLib;
28
- const callingFlowSharedLib = izaraShared.callingFlowSharedLib;
29
-
30
- const externalRequest = require('@izara_project/izara-core-library-external-request');
31
- const sns = externalRequest.sns;
32
- const getObjectSchema = require('@izara_project/izara-core-library-service-schemas/src/GetObjectSchema')
33
-
34
- const utils = require("@izara_project/izara-market-library-service-schemas/src/MainLibs/src/Utils");
35
- const NoRetryError = require("@izara_project/izara-core-library-core/src/NoRetryError");
36
-
37
- module.exports.main = middleware.wrap(async (event, context, callback) => {
38
-
39
- event._izContext.logger.debug('Event:', event);
40
-
41
- try {
42
-
43
- let eventParams = JSON.parse(event.body)
44
-
45
- if (event.requestContext) {
46
- const route = event.requestContext.routeKey;
47
- const connectionId = event.requestContext.connectionId;
48
-
49
- // const time = Date.now();
50
- // console.log(`socketxx: ${time}`);
51
-
52
- switch (route) {
53
- case null:
54
- console.log('Received unknown route:', route)
55
- break
56
- case 'webScoket':
57
- console.log("event in route", event)
58
- let callingFlow = eventParams?.callingFlow ? eventParams.callingFlow : {}
59
-
60
- let getFlowSchema = await getObjectSchema.getLocalFlowSchemas(event._izContext, eventParams.flowTag).then(res => res.records)
61
- event._izContext.logger.debug("getFlowSchema", getFlowSchema)
62
- let flowSchema = getFlowSchema[0]
63
- event._izContext.logger.debug("flowSchema", flowSchema);
64
-
65
- if (!flowSchema) {
66
- throw new NoRetryError(`flowTag not found ${flowSchema.flowTag}`)
67
- }
68
-
69
- // create messageObject send to topic
70
- let messageObject = {
71
- propertiesA: eventParams.propertiesA,
72
- }
73
-
74
- messageObject = callingFlowSharedLib.addPassBackPropertiesToSnsResponseMessageObject(callingFlow, messageObject);
75
-
76
- let messageAttributes = callingFlowSharedLib.addCallingFlowToSnsResponseMessageAttributes(callingFlow, {});
77
-
78
- let sendMessageToTopic = {
79
- Message: JSON.stringify(messageObject),
80
- MessageAttributes: messageAttributes,
81
- TopicArn: await snsSharedLib.snsTopicArn(event._izContext, `InProcess${utils.firstLetterLowerCase(flowSchema.flowTag)}`)
82
- }
83
-
84
- event._izContext.logger.debug(`message Params before send toInProcess${utils.firstLetterUpperCase(flowSchema.flowTag)}`, sendMessageToTopic);
85
- await sns.publishAsync(event._izContext, sendMessageToTopic)
86
-
87
-
88
- await dynamodbSharedLib.putItem(
89
- event._izContext,
90
- await dynamodbSharedLib.tableName(event._izContext, "WebSocketTask"),
91
- {
92
- taskKey: flowSchema.flowTag + connectionId,
93
- connectionid: connectionId
94
- }
95
- )
96
-
97
- postMessage(sendMessageToTopic, connectionId)
98
- break
99
- }
100
- } else {
101
- const connId = event.connId;
102
- await postMessage({ message: event.message }, connId);
103
- }
104
-
105
- return (izara.response.webSocketSuccess());
106
-
107
- } catch (err) {
108
- console.log("event", event)
109
- const connId = event.requestContext.connectionId
110
- event._izContext.logger.error('Error, WebSocket: ', err);
111
- await sendErrorMessage({ message: err.message }, connId);
112
- return (izara.response.failure(err));
113
- }
114
- });
115
-
116
- async function postMessage(data, connectionId) {
117
- const params = {
118
- ConnectionId: connectionId,
119
- Data: JSON.stringify(data),
120
- // Data: Buffer.from(JSON.stringify(data)),
121
- }
122
- return api.postToConnection(params).promise();
123
- };
124
-
125
- async function sendErrorMessage(errorMessage, connectionId) {
126
- const params = {
127
- ConnectionId: connectionId,
128
- Data: JSON.stringify(errorMessage)
129
- }
130
- return api.postToConnection(params).promise();
131
- }