@izara_project/izara-core-generate-service-code 1.0.73 → 1.0.75

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 (60) hide show
  1. package/package.json +1 -1
  2. package/src/emit/coreFunction/emitCoreFunctionArtifacts.js +3 -0
  3. package/src/emit/coreFunction/templates/InitialSetupConfig.ejs +100 -28
  4. package/src/emit/coreFunction/templates/InitialSetupRunner_uploadSchema.ejs +2 -0
  5. package/src/emit/coreFunction/templates/UploadSchema_Main.ejs +2 -0
  6. package/src/emit/crud/emitCrudApplicationArtifacts.js +2 -2
  7. package/src/emit/crud/emitDynamicCrudFlowSchemas.js +43 -2
  8. package/src/emit/crud/templates/CreateComplete_HdrSqs.ejs +99 -0
  9. package/src/emit/crud/templates/CreateComplete_Main.ejs +188 -0
  10. package/src/emit/crud/templates/DeleteComplete_HdrSqs.ejs +99 -0
  11. package/src/emit/crud/templates/DeleteComplete_Main.ejs +188 -0
  12. package/src/emit/crud/templates/FlowEndpointComplete_Main.ejs +1 -1
  13. package/src/emit/crud/templates/UpdateComplete_HdrSqs.ejs +99 -0
  14. package/src/emit/crud/templates/UpdateComplete_Main.ejs +188 -0
  15. package/src/emit/custom/customFlows.js +56 -0
  16. package/src/emit/custom/emitCustomFlowApplicationArtifacts.js +24 -9
  17. package/src/emit/custom/templates/FlowEndpoint_Main.ejs +1 -1
  18. package/src/emit/custom/templates/triggerCache/CheckTriggerCache_HdrSqs.ejs +2 -1
  19. package/src/emit/function/functionYamlArtifact.js +8 -3
  20. package/src/emit/relationship/emitDynamicRelationshipFlowSchemas.js +21 -1
  21. package/src/emit/relationship/emitRelationshipApplicationArtifacts.js +1 -1
  22. package/src/emit/relationship/templates/ChangeRelationshipComplete_HdrSqs.ejs +99 -0
  23. package/src/emit/relationship/templates/ChangeRelationshipComplete_Main.ejs +99 -100
  24. package/src/emit/relationship/templates/ChangeRelationship_Main.ejs +5 -14
  25. package/src/emit/relationship/templates/CreateRelationshipComplete_HdrSqs.ejs +99 -0
  26. package/src/emit/relationship/templates/CreateRelationshipComplete_Main.ejs +98 -99
  27. package/src/emit/relationship/templates/CreateRelationship_Main.ejs +7 -16
  28. package/src/emit/relationship/templates/DeleteRelationshipComplete_HdrSqs.ejs +99 -0
  29. package/src/emit/relationship/templates/DeleteRelationshipComplete_Main.ejs +93 -85
  30. package/src/emit/relationship/templates/DeleteRelationship_Main.ejs +6 -24
  31. package/src/emit/relationship/templates/GetRelationshipComplete_HdrSqs.ejs +99 -0
  32. package/src/emit/relationship/templates/GetRelationshipComplete_Main.ejs +10 -4
  33. package/src/emit/relationship/templates/GetRelationship_Main.ejs +2 -20
  34. package/src/emit/relationship/templates/MoveRelationshipComplete_HdrSqs.ejs +99 -0
  35. package/src/emit/relationship/templates/MoveRelationshipComplete_Main.ejs +101 -104
  36. package/src/emit/relationship/templates/MoveRelationship_Main.ejs +6 -15
  37. package/src/emit/relationship/templates/UpdateRelationshipComplete_HdrSqs.ejs +99 -0
  38. package/src/emit/relationship/templates/UpdateRelationshipComplete_Main.ejs +92 -110
  39. package/src/emit/relationship/templates/UpdateRelationship_Main.ejs +6 -15
  40. package/src/emit/resource/emitResourceArtifacts.js +25 -1
  41. package/src/emit/resource/templates/DynamoDBTable_Yaml.ejs +3 -0
  42. package/src/emit/shared/templates/FindData_Main.ejs +1 -1
  43. package/src/emit/shared/templates/FlowHandler_HdrApi.ejs +1 -1
  44. package/src/emit/shared/templates/FlowHandler_HdrDsq.ejs +2 -1
  45. package/src/emit/shared/templates/FlowHandler_HdrInv.ejs +1 -1
  46. package/src/emit/shared/templates/FlowHandler_HdrSqs.ejs +2 -1
  47. package/src/emit/system/emitSystemWebSocketArtifacts.js +54 -2
  48. package/src/emit/system/templates/RegisterComplete_HdrSqs.ejs +64 -0
  49. package/src/emit/system/templates/RegisterComplete_Main.ejs +154 -0
  50. package/src/emit/system/templates/RegisterComplete_Yaml.ejs +17 -0
  51. package/src/emit/system/templates/RegisterWbs_Yaml.ejs +7 -0
  52. package/src/emit/system/templates/Register_HdrWbs.ejs +56 -0
  53. package/src/emit/system/templates/Register_Main.ejs +148 -0
  54. package/src/emit/system/templates/WebSocketComplete_Yaml.ejs +2 -0
  55. package/test/crudApplicationArtifacts.test.js +22 -0
  56. package/test/customFlowApplicationArtifacts.test.js +147 -1
  57. package/test/functionYamlArtifact.test.js +5 -2
  58. package/test/publicApi.test.js +50 -0
  59. package/test/relationshipApplicationArtifacts.test.js +42 -8
  60. package/test/resourceArtifacts.test.js +54 -16
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@izara_project/izara-core-generate-service-code",
3
- "version": "1.0.73",
3
+ "version": "1.0.75",
4
4
  "description": "Code for locally generating per service files",
5
5
  "homepage": "https://bitbucket.org/izara-core-support-services/izara-core-support-services-generate-service-code#readme",
6
6
  "repository": {
@@ -1,6 +1,8 @@
1
1
  import ejsLib from 'ejs';
2
2
  import { readFile } from 'node:fs/promises';
3
3
 
4
+ import { customFlowNextSteps } from '../custom/customFlows.js';
5
+
4
6
  const TEMPLATE_URL = new URL('./templates/', import.meta.url);
5
7
  const APP_ROOT = 'app/sls_yaml/generatedCode/source';
6
8
  const SRC_ROOT = 'app/src/generatedCode/CoreFunctions';
@@ -94,6 +96,7 @@ export async function emitCoreFunctionArtifacts({ project, objects = [], relatio
94
96
  objects,
95
97
  relationships,
96
98
  flows,
99
+ customFlowNextSteps: customFlowNextSteps(flows),
97
100
  objectGraphServiceTags,
98
101
  relationshipGraphServiceTags,
99
102
  crud,
@@ -50,9 +50,9 @@ const externalServices = {
50
50
  const tableConfigs = {
51
51
  prod: {
52
52
  Config: {},
53
- <% dynamoTableNames.forEach(tableName => { -%>
54
- <%= tableName %>: {}
55
- <% }); -%>
53
+ <% dynamoTableNames.forEach(tableName => { -%>
54
+ <%= tableName %>: {},
55
+ <% }); -%>
56
56
  // <#InitialSetupConfig_ExtraProdTableConfigs#>
57
57
  // <#/InitialSetupConfig_ExtraProdTableConfigs#>
58
58
  },
@@ -61,11 +61,11 @@ const tableConfigs = {
61
61
  clearDataWhenRefresh: true,
62
62
  rawSource: false
63
63
  },
64
- <% dynamoTableNames.forEach(tableName => { -%>
64
+ <% dynamoTableNames.forEach(tableName => { -%>
65
65
  <%= tableName %>: {
66
66
  clearDataWhenRefresh: true
67
- }
68
- <% }); -%>
67
+ },
68
+ <% }); -%>
69
69
  // <#InitialSetupConfig_ExtraTestTableConfigs#>
70
70
  // <#/InitialSetupConfig_ExtraTestTableConfigs#>
71
71
  }
@@ -91,31 +91,31 @@ const tableConfigs = {
91
91
  });
92
92
  -%>
93
93
  const snsTopicSubscriptions = [
94
- <% if (relSubs.length > 0) { -%>
94
+ <% if (relSubs.length > 0) { -%>
95
95
  // ------------------------------------------------------------
96
96
  // Relationship Subscriptions
97
97
  // ------------------------------------------------------------
98
- <% relSubs.forEach(function(sub, idx) { -%>
98
+ <% relSubs.forEach(function(sub, idx) { -%>
99
99
  {
100
100
  serviceTag: '<%= sub.serviceTag %>',
101
101
  topicName: '<%= sub.topicName %>',
102
102
  sqsEndpoint: '<%= sub.sqsEndpoint %>'
103
103
  },
104
- <% }); -%>
105
- <% } -%>
106
- <% if (nodeSubs.length > 0) { -%>
104
+ <% }); -%>
105
+ <% } -%>
106
+ <% if (nodeSubs.length > 0) { -%>
107
107
 
108
108
  // ------------------------------------------------------------
109
109
  // Node Subscriptions
110
110
  // ------------------------------------------------------------
111
- <% nodeSubs.forEach(function(sub, idx) { -%>
111
+ <% nodeSubs.forEach(function(sub, idx) { -%>
112
112
  {
113
113
  serviceTag: '<%= sub.serviceTag %>',
114
114
  topicName: '<%= sub.topicName %>',
115
115
  sqsEndpoint: '<%= sub.sqsEndpoint %>'
116
116
  },
117
- <% }); -%>
118
- <% } -%>
117
+ <% }); -%>
118
+ <% } -%>
119
119
 
120
120
  //(<additionalSubscription>)
121
121
  //(</additionalSubscription>)
@@ -126,11 +126,11 @@ const snsTopicSubscriptions = [
126
126
  // ============================================================
127
127
  function roleConfigs() {
128
128
  const externalLambdaRole = [
129
- <% if (crud && objectGraphServiceTags && objectGraphServiceTags.length > 0) { -%>
129
+ <% if (crud && objectGraphServiceTags && objectGraphServiceTags.length > 0) { -%>
130
130
  {
131
131
  roleName: 'FlowObjects',
132
132
  statement: [
133
- <% objectGraphServiceTags.forEach(function(tag, idx) { -%>
133
+ <% objectGraphServiceTags.forEach(function(tag, idx) { -%>
134
134
  {
135
135
  Sid: 'FlowObjectsInvokeGetNode<%= tag %>',
136
136
  Effect: 'Allow',
@@ -149,7 +149,7 @@ function roleConfigs() {
149
149
  `arn:aws:sns:${process.env.iz_region}:${process.env.iz_accountId}:${snsSharedLib.snsTopicNameByFlowSchema(_izContext, 'CreateNode_In', '<%= tag %>')}`
150
150
  ]
151
151
  },
152
- <% }); -%>
152
+ <% }); -%>
153
153
  //(<createFlowObjectsRole>)
154
154
  //(</createFlowObjectsRole>)
155
155
  ]
@@ -158,7 +158,7 @@ function roleConfigs() {
158
158
  {
159
159
  roleName: 'ProcFindData',
160
160
  statement: [
161
- <% objectGraphServiceTags.forEach(function(tag, idx) { -%>
161
+ <% objectGraphServiceTags.forEach(function(tag, idx) { -%>
162
162
  {
163
163
  Sid: 'ProcFindDataInvokeGetNode<%= tag %>',
164
164
  Effect: 'Allow',
@@ -167,18 +167,17 @@ function roleConfigs() {
167
167
  `arn:aws:lambda:${process.env.iz_region}:${process.env.iz_accountId}:function:${lambdaSharedLib.lambdaFunctionName(_izContext, 'GetNodeHdrInv', '<%= tag %>')}`
168
168
  ]
169
169
  }
170
- <% }); -%>
170
+ <% }); -%>
171
171
  //(<createProcFindDataRole>)
172
172
  //(</createProcFindDataRole>)
173
173
  ]
174
174
  },
175
- <% } -%>
176
-
177
- <% if (hasRelationships && relationshipGraphServiceTags && relationshipGraphServiceTags.length > 0) { -%>
175
+ <% } -%>
176
+ <% if (hasRelationships && relationshipGraphServiceTags && relationshipGraphServiceTags.length > 0) { -%>
178
177
  {
179
178
  roleName: 'FlowRelationship',
180
179
  statement: [
181
- <% relationshipGraphServiceTags.forEach(function(tag, idx) { -%>
180
+ <% relationshipGraphServiceTags.forEach(function(tag, idx) { -%>
182
181
  {
183
182
  Sid: 'FlowRelationshipInvokeGetRelationship<%= tag %>',
184
183
  Effect: 'Allow',
@@ -200,13 +199,14 @@ function roleConfigs() {
200
199
  `arn:aws:sns:${process.env.iz_region}:${process.env.iz_accountId}:${snsSharedLib.snsTopicNameByFlowSchema(_izContext, 'MoveRelationship_In', '<%= tag %>')}`
201
200
  ]
202
201
  }
203
- <% }); -%>
202
+ <% }); -%>
204
203
  //(<createFlowRelationshipRole>)
205
204
  //(</createFlowRelationshipRole>)
206
205
  ]
207
- }
208
- <% } -%>
209
- <% s3Flows.forEach(function(flow) { -%> {
206
+ },
207
+ <% } -%>
208
+ <% s3Flows.forEach(function(flow) { -%>
209
+ {
210
210
  roleName: '<%= flow.roleName %>',
211
211
  statement: [
212
212
  {
@@ -229,7 +229,79 @@ function roleConfigs() {
229
229
  //(<create<%= flow.roleName %>Role>)
230
230
  //(</create<%= flow.roleName %>Role>)
231
231
  ]
232
- } <% }); %>
232
+ },
233
+ <% }); -%>
234
+ <%
235
+ let nextStepsFlows = [];
236
+ if (typeof customFlowNextSteps !== 'undefined' && customFlowNextSteps) {
237
+ nextStepsFlows = customFlowNextSteps;
238
+ }
239
+ for (let flowIdx = 0; flowIdx < nextStepsFlows.length; flowIdx++) {
240
+ const flow = nextStepsFlows[flowIdx];
241
+ const snsTopicItems = [];
242
+ const lambdaInvItems = [];
243
+ for (const s of flow.nextSteps) {
244
+ if (s.targetType === 'extTopic' || s.targetType === 'ownTopic') {
245
+ snsTopicItems.push(s);
246
+ } else if (s.targetType === 'lambdaSyncInv') {
247
+ lambdaInvItems.push(s);
248
+ }
249
+ }
250
+ -%>
251
+ {
252
+ roleName: '<%= flow.roleName %>',
253
+ statement: [
254
+ <% if (snsTopicItems.length > 0) { -%>
255
+ {
256
+ Sid: '<%= flow.roleName %>PublishNextStepsTopics',
257
+ Effect: 'Allow',
258
+ Action: ['sns:Publish'],
259
+ Resource: [
260
+ <%
261
+ for (let idx = 0; idx < snsTopicItems.length; idx++) {
262
+ const item = snsTopicItems[idx];
263
+ let tagArg = '';
264
+ if (item.serviceTag) {
265
+ tagArg = `, '${item.serviceTag}'`;
266
+ }
267
+ let comma = '';
268
+ if (idx < snsTopicItems.length - 1) {
269
+ comma = ',';
270
+ }
271
+ -%>
272
+ `arn:aws:sns:${process.env.iz_region}:${process.env.iz_accountId}:${snsSharedLib.snsTopicNameByFlowSchema(_izContext, '<%- item.topic %>'<%- tagArg %>)}`<%= comma %>
273
+ <% } -%>
274
+ ]
275
+ }<% if (lambdaInvItems.length > 0) { %>,<% } %>
276
+ <% } -%>
277
+ <% if (lambdaInvItems.length > 0) { -%>
278
+ {
279
+ Sid: '<%= flow.roleName %>InvokeNextStepsFunctions',
280
+ Effect: 'Allow',
281
+ Action: ['lambda:InvokeFunction'],
282
+ Resource: [
283
+ <%
284
+ for (let idx = 0; idx < lambdaInvItems.length; idx++) {
285
+ const item = lambdaInvItems[idx];
286
+ let tagArg = '';
287
+ if (item.serviceTag) {
288
+ tagArg = `, '${item.serviceTag}'`;
289
+ }
290
+ let comma = '';
291
+ if (idx < lambdaInvItems.length - 1) {
292
+ comma = ',';
293
+ }
294
+ -%>
295
+ `arn:aws:lambda:${process.env.iz_region}:${process.env.iz_accountId}:function:${lambdaSharedLib.lambdaFunctionName(_izContext, '<%- item.topic %>'<%- tagArg %>)}`<%= comma %>
296
+ <% } -%>
297
+ ]
298
+ }
299
+ <% } -%>
300
+ //(<create<%= flow.roleName %>Role>)
301
+ //(</create<%= flow.roleName %>Role>)
302
+ ]
303
+ }<% if (flowIdx < nextStepsFlows.length - 1) { %>,<% } %>
304
+ <% } -%>
233
305
  //(<additionalRole>)
234
306
  //(</additionalRole>)
235
307
  ];
@@ -8,6 +8,7 @@ const SERVICE_TAG = {
8
8
  MEDIA: 'Media'
9
9
  };
10
10
 
11
+ //(<ignoreExternalServices>)
11
12
  const ignoreExternalServices = {
12
13
  [SERVICE_TAG.TRANSLATIONS]: false,
13
14
  [SERVICE_TAG.GRAPH_HANDLER]: false,
@@ -15,6 +16,7 @@ const ignoreExternalServices = {
15
16
  [SERVICE_TAG.TRANSLATE_IDS]: false,
16
17
  [SERVICE_TAG.MEDIA]: false
17
18
  };
19
+ //(</ignoreExternalServices>)
18
20
 
19
21
  export default async function uploadSchema(_izContext) {
20
22
  console.log('======== UploadSchema ========');
@@ -25,6 +25,7 @@ const SERVICE_TAG = {
25
25
  MEDIA: 'Media'
26
26
  };
27
27
 
28
+ //(<ignoreExternalServices>)
28
29
  const ignoreExternalServices = {
29
30
  [SERVICE_TAG.TRANSLATIONS]: false,
30
31
  [SERVICE_TAG.GRAPH_HANDLER]: false,
@@ -32,6 +33,7 @@ const ignoreExternalServices = {
32
33
  [SERVICE_TAG.TRANSLATE_IDS]: false,
33
34
  [SERVICE_TAG.MEDIA]: false
34
35
  };
36
+ //(</ignoreExternalServices>)
35
37
 
36
38
  const uploadSchema = async (_izContext) => {
37
39
  try {
@@ -234,11 +234,11 @@ async function emitAction(action, objects, flows, serviceTag) {
234
234
  artifacts.push(
235
235
  {
236
236
  path: `${source}/${complete}_Main.js`,
237
- content: await render('FlowEndpointComplete_Main.ejs', { action })
237
+ content: await render(`${action}Complete_Main.ejs`, { action })
238
238
  },
239
239
  {
240
240
  path: `${source}/${complete}_HdrSqs.js`,
241
- content: await renderShared('FlowHandler_HdrSqs.ejs', {
241
+ content: await render(`${action}Complete_HdrSqs.ejs`, {
242
242
  ...shared,
243
243
  mainFileName: `${complete}_Main`,
244
244
  functionName: complete,
@@ -23,7 +23,10 @@ export function emitDynamicCrudFlowSchemas({ objects, flows = [] }) {
23
23
  }
24
24
 
25
25
  return ACTIONS.map((action, index) => {
26
- const flow = _createDynamicFlow(action, _hasBeforeLogicalStep(flows, action));
26
+ const flow = _createDynamicFlow(
27
+ action,
28
+ _hasBeforeLogicalStep(flows, action)
29
+ );
27
30
  return {
28
31
  path: dynamicCrudFlowSchemaPaths[index],
29
32
  content: renderDynamicCrudFlowSchema(action, flow)
@@ -36,6 +39,23 @@ function _createDynamicFlow(action, hasBeforeLogicalStep) {
36
39
  const flowSteps = [
37
40
  {
38
41
  stepName: 'start',
42
+ ...(hasBeforeLogicalStep
43
+ ? {
44
+ nextSteps: [
45
+ {
46
+ stepName: 'BeforeLogical'
47
+ }
48
+ ]
49
+ }
50
+ : outputTopic
51
+ ? {
52
+ nextSteps: [
53
+ {
54
+ stepName: 'Complete'
55
+ }
56
+ ]
57
+ }
58
+ : {}),
39
59
  properties: [],
40
60
  messageAttributes: MESSAGE_ATTRIBUTES,
41
61
  ...(outputTopic
@@ -53,6 +73,16 @@ function _createDynamicFlow(action, hasBeforeLogicalStep) {
53
73
  flowSteps.push({
54
74
  stepName: 'BeforeLogical',
55
75
  event: ['extTopic'],
76
+ previousSteps: [
77
+ {
78
+ stepName: 'start'
79
+ }
80
+ ],
81
+ nextSteps: [
82
+ {
83
+ stepName: 'Complete'
84
+ }
85
+ ],
56
86
  properties: [],
57
87
  messageAttributes: MESSAGE_ATTRIBUTES
58
88
  });
@@ -62,7 +92,18 @@ function _createDynamicFlow(action, hasBeforeLogicalStep) {
62
92
  flowSteps.push({
63
93
  stepName: 'Complete',
64
94
  event: ['extTopic'],
65
- properties: [],
95
+ previousSteps: [
96
+ {
97
+ stepName: hasBeforeLogicalStep ? 'BeforeLogical' : 'start'
98
+ }
99
+ ],
100
+ properties: [
101
+ 'returnValue',
102
+ 'parentFlowId',
103
+ 'status',
104
+ 'errorsFound',
105
+ 'graphServiceTag'
106
+ ],
66
107
  messageAttributes: MESSAGE_ATTRIBUTES
67
108
  });
68
109
  }
@@ -0,0 +1,99 @@
1
+ import { middlewareHandler as middleware } from '@izara_project/izara-middleware';
2
+ import { recordHandlerSharedLib } from '@izara_project/izara-core-library-record-handler';
3
+ import Logger from '@izara_project/izara-core-library-logger';
4
+ import callingFlowSharedLib from '@izara_project/izara-core-library-calling-flow';
5
+ import CreateComplete from './CreateComplete_Main.js';
6
+
7
+ //(<optionalRequire>)
8
+ //(</optionalRequire>)
9
+
10
+ // validate event properties in body.Message of sqs event
11
+ let perRecordsValidatorSchema = {
12
+ type: 'object',
13
+ properties: {
14
+ returnValue: {
15
+ type: 'object'
16
+ },
17
+ parentFlowId: {
18
+ type: 'string'
19
+ },
20
+ status: {
21
+ type: 'string'
22
+ },
23
+ errorsFound: {
24
+ type: 'array'
25
+ },
26
+ graphServiceTag: {
27
+ type: 'string'
28
+ }
29
+ },
30
+ required: [
31
+ 'returnValue',
32
+ 'parentFlowId',
33
+ 'status',
34
+ 'errorsFound',
35
+ 'graphServiceTag'
36
+ ]
37
+ //(<validatorSchema>)
38
+ //(</validatorSchema>)
39
+ };
40
+
41
+ let messageAttributeValidatorSchema = null;
42
+ middleware.setValidatorSchema(recordHandlerSharedLib.baseValidatorSchema());
43
+
44
+ export const main = middleware.wrap(async (event, context) => {
45
+ try {
46
+ let recordPromises = [];
47
+
48
+ // loop each record and send to mainFunction
49
+ await Promise.all(
50
+ event.Records.map(async (record) => {
51
+ let passOnProperties = [];
52
+ record._izContext.logger.debug('record ReceiveMsgOutHdrSqs', record);
53
+
54
+ //validate message (and MessageAttributes)
55
+ await recordHandlerSharedLib.validateRecord(
56
+ record, // one record will send to mainFunction
57
+ 'CreateCompleteHdrSqs', // queue name that need to retry or send to dlq
58
+ perRecordsValidatorSchema, // schema for record.Message
59
+ messageAttributeValidatorSchema
60
+ );
61
+
62
+ // add argument (to invoke lambda) to passOnProperties[]
63
+ passOnProperties.push(record.body.Message);
64
+ passOnProperties.push(
65
+ callingFlowSharedLib.addPassBackPropertiesToPassOnProperties(
66
+ record.body.Message
67
+ )
68
+ );
69
+ //(<additionalParams>)
70
+ //(</additionalParams>)
71
+ record._izContext.logger.debug(
72
+ 'passOnProperties in handler',
73
+ passOnProperties
74
+ );
75
+
76
+ // call recordHandlerSharedLib.recordHandler with 3 parameters and return promise(resolve)
77
+ let recordPromise = recordHandlerSharedLib.recordHandler(
78
+ record, // one record will send to mainFunction
79
+ CreateComplete, // mainFunction that need to invoke.
80
+ 'CreateCompleteHdrSqs', // queue name that need to retry or send to dlq
81
+ passOnProperties // all parameters that mainFunction needed.
82
+ );
83
+ record._izContext.logger.debug('after recordPromise in handler');
84
+ recordPromises.push(recordPromise); // push promise to recordPromises
85
+ })
86
+ );
87
+ try {
88
+ await Promise.all(recordPromises);
89
+ return event.Records;
90
+ } catch {
91
+ Logger.debug(
92
+ 'Promise.all(recordPromises) in handler threw error (at least one record did no resolve)'
93
+ );
94
+ }
95
+ } catch (error) {
96
+ Logger.error('Unhandled Error, CreateComplete_HdrSqs: ', error);
97
+ throw error;
98
+ }
99
+ });
@@ -0,0 +1,188 @@
1
+ import asyncFlowSharedLib from '@izara_project/izara-core-library-asynchronous-flow';
2
+ import callingFlowSharedLib from '@izara_project/izara-core-library-calling-flow';
3
+ import dynamodbSharedLib from '@izara_project/izara-core-library-dynamodb';
4
+ import snsSharedLib from '@izara_project/izara-core-library-sns';
5
+ import { sns } from '@izara_project/izara-core-library-external-request';
6
+ import { consts } from '@izara_project/izara-core-library-service-schemas';
7
+ import { NoRetryError } from '@izara_project/izara-core-library-core';
8
+
9
+ //(<optionalRequire>)
10
+ //(</optionalRequire>)
11
+
12
+ const { TOPIC_NAME_GENERATE_CODE } = consts;
13
+ const PREFIX = { ASYNC: 'CreateAsyncEndpoint' };
14
+
15
+ function empty(value) {
16
+ return (
17
+ value == null ||
18
+ (typeof value === 'object' && Object.keys(value).length === 0)
19
+ );
20
+ }
21
+
22
+ function validateInput(returnValue, status, graphServiceTag, errorsFound) {
23
+ if (!returnValue?.queryResult)
24
+ errorsFound.push(
25
+ 'message is not have property queryResult, should be not happen'
26
+ );
27
+ if (!returnValue?.requestParams?.objType)
28
+ errorsFound.push(
29
+ 'message is not have property objType, should be not happen'
30
+ );
31
+ if (!returnValue?.requestParams?.objInstanceFull)
32
+ errorsFound.push(
33
+ 'message is not have property objInstance, should be not objInstance'
34
+ );
35
+ if (status === 'error' && errorsFound.length === 0)
36
+ errorsFound.push(
37
+ '[invalid]status is error not have errorsFound form graphService'
38
+ );
39
+ if (status === 'complete' && errorsFound.length > 0)
40
+ errorsFound.push(
41
+ '[Invalid] status is complete should be not have errorsFound'
42
+ );
43
+ if (graphServiceTag == null)
44
+ errorsFound.push('[Invalid] graphServerTag is not empty string');
45
+ }
46
+
47
+ export default async function CreateComplete(
48
+ _izContext,
49
+ requestParams,
50
+ passBackProperties
51
+ //(<additionalParams>)
52
+ //(</additionalParams>)
53
+ ) {
54
+ try {
55
+ _izContext.logger.debug('[CreateComplete] started', {
56
+ requestParams
57
+ });
58
+ const {
59
+ returnValue,
60
+ status,
61
+ errorsFound = [],
62
+ graphServiceTag,
63
+ parentFlowId
64
+ } = requestParams;
65
+ if (empty(returnValue?.requestParams))
66
+ throw new NoRetryError('message not an object');
67
+ validateInput(returnValue, status, graphServiceTag, errorsFound);
68
+ if (errorsFound.length > 0) errorsFound.push(errorsFound.join(','));
69
+
70
+ const awaitingStepId = await asyncFlowSharedLib.createAwaitingStepId(
71
+ parentFlowId,
72
+ PREFIX.ASYNC
73
+ );
74
+ const pending =
75
+ await asyncFlowSharedLib.findPendingStepAwaitingMultipleSteps(
76
+ _izContext,
77
+ awaitingStepId
78
+ );
79
+ _izContext.logger.debug('[CreateComplete] awaiting step', {
80
+ awaitingStepId,
81
+ pending
82
+ });
83
+ if (!pending) {
84
+ _izContext.logger.warn(
85
+ `No pending step found for awaitingStepId: ${awaitingStepId}`
86
+ );
87
+ return { returnValue, status, errorsFound };
88
+ }
89
+ const result =
90
+ await asyncFlowSharedLib.checkAllAwaitingStepsFinishedWithReturnParams(
91
+ _izContext,
92
+ pending.pendingStepId,
93
+ awaitingStepId,
94
+ errorsFound
95
+ );
96
+ _izContext.logger.debug(
97
+ '[CreateComplete] all awaiting steps result',
98
+ {
99
+ isComplete: result.isComplete,
100
+ awaitingStepId,
101
+ pendingStepId: pending.pendingStepId
102
+ }
103
+ );
104
+
105
+ if (result.isComplete) {
106
+ const nodeResultKey = `returnCreatedNode`;
107
+ const fallbackNodeResultKey = `returnCreateNode`;
108
+ const nodeResult =
109
+ returnValue.queryResult[nodeResultKey] ??
110
+ returnValue.queryResult[fallbackNodeResultKey] ??
111
+ {};
112
+ const node = nodeResult.createNodeResult ?? nodeResult;
113
+ const existsNode =
114
+ node.existsNode && Object.keys(node.existsNode).length
115
+ ? {
116
+ objType: returnValue.requestParams.objType,
117
+ objInstanceFull: node.existsNode.objInstanceFull
118
+ }
119
+ : null;
120
+ if (status === 'complete') {
121
+ await Promise.all(
122
+ (pending.listOfRecords ?? []).flatMap((records) =>
123
+ Object.values(records).map(async (record) =>
124
+ dynamodbSharedLib.putItem(
125
+ _izContext,
126
+ await dynamodbSharedLib.tableName(
127
+ _izContext,
128
+ record.tableName,
129
+ record.serviceTag
130
+ ),
131
+ {
132
+ ...record.objInstanceFull.identifiers,
133
+ ...record.objInstanceFull.fields
134
+ }
135
+ )
136
+ )
137
+ )
138
+ );
139
+ }
140
+ const message =
141
+ callingFlowSharedLib.addParentPassBackPropertiesToSnsResponseMessageObject(
142
+ passBackProperties,
143
+ {
144
+ objType: returnValue.requestParams.objType,
145
+ objInstanceFull: node.objInstanceFull,
146
+ relationships: node.relationships,
147
+ parentFlowId: parentFlowId || returnValue?.parentFlowId,
148
+ existsNode,
149
+ status,
150
+ errorsFound
151
+ }
152
+ );
153
+ const messageAttributes =
154
+ callingFlowSharedLib.addParentPassBackCallingFlowToSnsResponseMessageAttributes(
155
+ passBackProperties,
156
+ {}
157
+ );
158
+ const topicArn = snsSharedLib.snsTopicArnByFlowSchema(
159
+ _izContext,
160
+ TOPIC_NAME_GENERATE_CODE.outCreateNodeComplete
161
+ );
162
+ _izContext.logger.debug('[CreateComplete] publishing to SNS', {
163
+ TopicArn: topicArn,
164
+ message
165
+ });
166
+ await sns.publishAsync(_izContext, {
167
+ Message: JSON.stringify(message),
168
+ MessageAttributes: sns.createStringMessageAttributes(
169
+ _izContext,
170
+ messageAttributes
171
+ ),
172
+ TopicArn: topicArn
173
+ });
174
+ //(<afterSendMessage>)
175
+ //(</afterSendMessage>)
176
+ }
177
+ await asyncFlowSharedLib.removeAwaitingMultipleStep(
178
+ _izContext,
179
+ awaitingStepId,
180
+ pending.pendingStepId,
181
+ errorsFound
182
+ );
183
+ return { returnValue, status, errorsFound };
184
+ } catch (error) {
185
+ _izContext.logger.error('[CreateComplete] error:', error);
186
+ throw error;
187
+ }
188
+ }