@izara_project/izara-market-library-service-schemas 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.
package/index.js CHANGED
@@ -17,14 +17,18 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
17
17
 
18
18
  'use strict';
19
19
 
20
-
21
-
22
20
  module.exports = {
23
21
  templateMgr: require('./src/TemplateManager'),
24
22
  sourceMgr: require('./src/SourceManager'),
25
23
  generateCodeLibs: require('./src/GenerateCodeLibs'),
26
24
  utils: require('./src/MainLibs'),
27
- generateSchemaWithTemplate: require('./src/TemplateManager/src/GenerateSchema').generateSchemaWithTemplate,
28
- generateCodeWithTemplate: require('./src/reStructure/GenerateCode').generateCodeWithTemplate,
29
- generateSchema: require('./src/reStructure/GenerateSchema')
30
- }
25
+ generateSchemaWithTemplate:
26
+ require('./src/TemplateManager/src/GenerateSchema')
27
+ .generateSchemaWithTemplate,
28
+ generateCodeWithTemplate: require('./src/reStructure/GenerateCode')
29
+ .generateCodeWithTemplate,
30
+ generateSchema: require('./src/reStructure/GenerateSchema'),
31
+
32
+ // Libs
33
+ checkPermission: require('./src/CheckPermission')
34
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@izara_project/izara-market-library-service-schemas",
3
- "version": "1.0.73",
3
+ "version": "1.0.75",
4
4
  "description": "Schemas for Izara Market project",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -14,26 +14,27 @@
14
14
  "license": "AGPL-3.0-or-later",
15
15
  "homepage": "https://bitbucket.org/izara-market-libraries/izara-market-library-service-schemas/src/master/README.md",
16
16
  "devDependencies": {
17
- "jest": "^30.0.5"
17
+ "jest": "^30.2.0"
18
18
  },
19
19
  "jest": {
20
20
  "testEnvironment": "node"
21
21
  },
22
22
  "dependencies": {
23
23
  "@izara_project/izara-core-library-calling-flow": "^1.0.3",
24
- "@izara_project/izara-core-library-core": "^1.0.20",
25
- "@izara_project/izara-core-library-external-request": "^1.0.20",
24
+ "@izara_project/izara-core-library-core": "^1.0.27",
25
+ "@izara_project/izara-core-library-external-request": "^1.0.21",
26
+ "@izara_project/izara-core-library-lambda": "^1.0.5",
26
27
  "@izara_project/izara-core-library-logger": "^1.0.7",
27
- "@izara_project/izara-core-library-service-schemas": "^1.0.96",
28
+ "@izara_project/izara-core-library-service-schemas": "^1.0.100",
28
29
  "@izara_project/izara-core-library-sns": "^1.0.6",
29
30
  "@izara_project/izara-core-library-sqs": "^1.0.4",
30
31
  "@izara_project/izara-shared": "^1.0.126",
31
- "@izara_project/izara-shared-service-schemas": "^1.0.31",
32
- "@izara_project/izara-shared-core": "^1.0.2",
32
+ "@izara_project/izara-shared-core": "^1.0.4",
33
+ "@izara_project/izara-shared-service-schemas": "^1.0.32",
33
34
  "ejs": "^3.1.10",
34
35
  "js-beautify": "^1.15.4",
35
36
  "lodash": "^4.17.21",
36
37
  "object-hash": "^3.0.0",
37
- "yaml": "^2.8.0"
38
+ "yaml": "^2.8.1"
38
39
  }
39
40
  }
@@ -0,0 +1,140 @@
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
+ /*
19
+ Copyright (C) 2020 Sven Mason <http://izara.io>
20
+
21
+ This program is free software: you can redistribute it and/or modify
22
+ it under the terms of the GNU Affero General Public License as
23
+ published by the Free Software Foundation, either version 3 of the
24
+ License, or (at your option) any later version.
25
+
26
+ This program is distributed in the hope that it will be useful,
27
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
28
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29
+ GNU Affero General Public License for more details.
30
+
31
+ You should have received a copy of the GNU Affero General Public License
32
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
33
+ */
34
+
35
+ 'use strict';
36
+
37
+ const {
38
+ lambdaFunctionName
39
+ } = require('@izara_project/izara-core-library-lambda');
40
+ const {
41
+ lambda
42
+ } = require('@izara_project/izara-core-library-external-request');
43
+ const { consts } = require('@izara_project/izara-core-library-core');
44
+
45
+ /**
46
+ * Checks a user's permission by invoking another Lambda function.
47
+ * Adheres to Izara.io backend syntax guidelines.
48
+ *
49
+ * @param {object} _izContext - The context object containing logger, credentials, etc.
50
+ * @param {object} payload - The data payload for the permission check.
51
+ * @param {string} [payload.objectType] - The type of the object (e.g., 'INVOICE'). Must be used with `action`.
52
+ * @param {string} [payload.action] - The action to perform (e.g., 'READ', 'APPROVE'). Must be used with `objectType`.
53
+ * @param {string} [payload.flowTag] - The tag for a flow-based permission check. Used instead of `objectType`/`action`.
54
+ * @param {string} [payload.serviceName] - The name of the calling service (optional).
55
+ * @returns {Promise<void>} - Resolves on successful invocation, rejects on error.
56
+ * @throws {Error} If the payload data is invalid or if the Lambda invocation fails.
57
+ */
58
+ async function checkPermission(_izContext, payload) {
59
+ // Validate that the payload object itself is provided.
60
+ if (!payload || typeof payload !== 'object') {
61
+ const error = new Error('Payload object is required.');
62
+ _izContext.logger.error(error.message);
63
+ throw error;
64
+ }
65
+
66
+ const userId = _izContext.correlationIds.get(consts.BASE_USER_ID);
67
+ const targetId = _izContext.correlationIds.get(consts.TARGET_ID);
68
+
69
+ // Validate the required 'userId' field.
70
+ if (!userId || typeof userId !== 'string' || userId.trim() === '') {
71
+ const error = new Error(
72
+ 'userId is required and must be a non-empty string.'
73
+ );
74
+ _izContext.logger.error(error.message);
75
+ throw error;
76
+ } else {
77
+ payload.userId = userId;
78
+ }
79
+
80
+ if (targetId) {
81
+ payload.targetId = targetId;
82
+ }
83
+
84
+ // Define validation flags for business rules.
85
+ const hasObjectParams = payload.objectType || payload.action;
86
+ const hasFlowTag = payload.flowTag;
87
+
88
+ // Rule: Cannot mix object-based and flow-based parameters.
89
+ if (hasObjectParams && hasFlowTag) {
90
+ const error = new Error(
91
+ 'Invalid payload: Cannot provide flowTag together with objectType or action.'
92
+ );
93
+ _izContext.logger.error(error.message, { payload });
94
+ throw error;
95
+ }
96
+
97
+ // Rule: If using object-based, both objectType and action are required.
98
+ if (hasObjectParams && (!payload.objectType || !payload.action)) {
99
+ const error = new Error(
100
+ 'Invalid payload: Both objectType and action must be provided together.'
101
+ );
102
+ _izContext.logger.error(error.message, { payload });
103
+ throw error;
104
+ }
105
+
106
+ // Rule: Must provide at least one of the two valid schemas.
107
+ if (!hasObjectParams && !hasFlowTag) {
108
+ const error = new Error(
109
+ 'Invalid payload: Must provide either (objectType and action) or flowTag.'
110
+ );
111
+ _izContext.logger.error(error.message, { payload });
112
+ throw error;
113
+ }
114
+
115
+ // Log the payload for debugging before invoking the next service.
116
+ _izContext.logger.debug('Checking permission with payload:', payload);
117
+
118
+ try {
119
+ const lambdaName = await lambdaFunctionName(
120
+ _izContext,
121
+ 'CheckPermissionHdrInv',
122
+ 'UserAccount'
123
+ );
124
+
125
+ await lambda.invokeSync(_izContext, lambdaName, payload);
126
+
127
+ _izContext.logger.info('Permission check invoked successfully.');
128
+ } catch (err) {
129
+ // Log the full error object for better traceability.
130
+ _izContext.logger.error(
131
+ 'Error invoking CheckPermissionHdrInv Lambda: ',
132
+ err
133
+ );
134
+ throw err;
135
+ }
136
+ }
137
+
138
+ module.exports = {
139
+ checkPermission
140
+ };
@@ -34,6 +34,7 @@ const NoRetryError = require('@izara_project/izara-core-library-core').NoRetryEr
34
34
  const triggeredCacheSharedLib = require('@izara_project/izara-core-library-trigger-cache')
35
35
  <% } else if (statusType === "statusField") { -%>
36
36
  const { createFieldNamesFromRequestParamsByObjectSchema } = require('@izara_project/izara-market-library-service-schemas/src/GenerateCodeLibs/src/GenerateCodeLibs.js')
37
+ const statusFieldSharedLib = require('@izara_project/izara-core-library-status-field')
37
38
  <% } else if (statusType === "storedCache") { -%>
38
39
  const storedCacheSharedLib = require('@izara_project/izara-core-library-stored-cache')
39
40
  <% } -%>
@@ -69,9 +70,9 @@ module.exports.<%- functionName %> = async (
69
70
  _izContext.logger.debug("<%- functionName %> callingFlowConfig", callingFlowConfig)
70
71
 
71
72
  <% if (statusType === "statusField") { %>
72
- <%- include(statusFieldTemplate) %>
73
+ <%- include(statusFieldTemplate, { tableName:tableName, flowTag: flowTag }) %>
73
74
  <% } else if (statusType === "storedCache") { %>
74
- <%- include(storedCacheTemplate, {tableName:tableName, flowSchemaComplete:flowSchemaComplete,flowTag}) %>
75
+ <%- include(storedCacheTemplate, { tableName:tableName, flowSchemaComplete:flowSchemaComplete,flowTag }) %>
75
76
 
76
77
  <% } else if (statusType === "triggerCache") { %>
77
78
  <%- include(triggerCacheTemplate, {
@@ -154,6 +154,13 @@ const createFlowSchemaTriggerCacheMainFunction = {
154
154
  createTriggerCacheCompleteMainFunction: require('./triggerCacheComponent/triggerCacheComplete/mainFunction/data')
155
155
  }
156
156
  const createFlowSchemaTriggerCacheQueue = require('./triggerCacheComponent/triggerCacheQueue/data')
157
+
158
+ const createFlowSchemaStatusFieldComponent = {
159
+ createCompleteStatusFieldMainFunction: require('./statusFieldComponent/MainFunction/data'),
160
+ createCompleteStatusFieldFunctionYaml: require('./statusFieldComponent/FunctionYaml/data'),
161
+ createCompleteStatusFieldHandler: require('./statusFieldComponent/Handler/data'),
162
+ createCompleteStatusFieldTopicAndQueue: require('./statusFieldComponent/sns/data')
163
+ }
157
164
  /**
158
165
  * Generates code with templates for different actions
159
166
  * @param {Object} _izContext - Context object
@@ -358,6 +365,11 @@ async function generateCodeWithTemplate(_izContext, objSchemaPath) {
358
365
  console.log("event ownTopic generated")
359
366
  createSourceParams.push(...ownTopicResources);
360
367
 
368
+ if (flowSchema.outputTopic === true && flowSchema.event.includes("ownTopic") || flowSchema.event.includes("extTopic")) {
369
+ const statusFieldComponent = (await Promise.all(Object.entries(createFlowSchemaStatusFieldComponent).map(([type, functionYaml]) => functionYaml(_izContext, flowSchema, saveFilePath)))).flat();;
370
+ console.log("statusFieldComponent", JSON.stringify(statusFieldComponent, null, 2))
371
+ createSourceParams.push(...statusFieldComponent)
372
+ }
361
373
  } else if (event.includes("eventBridge")) {
362
374
 
363
375
  const flowSchemaEventBridgeHandler = createFlowSchemaEventBridgeHandler(_izContext, flowSchema, saveFilePath);
@@ -443,10 +455,7 @@ async function generateCodeWithTemplate(_izContext, objSchemaPath) {
443
455
  const queue = createFlowSchemaTriggerCacheQueue(flowSchema, saveFilePath);
444
456
  // console.log("functionYaml", JSON.stringify(...functionYaml, null, 2))
445
457
  createSourceParams.push(...functionYaml, ...mainFunction, ...handler, ...queue)
446
- // console.log("createSourceParams triggerCache", JSON.stringify(createSourceParams, null, 2))
447
- console.log("mainFunction triggerCache", JSON.stringify(mainFunction, null, 2))
448
- console.log("handler triggerCache", JSON.stringify(handler, null, 2))
449
- console.log("Generate triggerCache component")
458
+ // console.log("Generate triggerCache component")
450
459
  }
451
460
  }
452
461
 
@@ -478,7 +487,7 @@ async function generateCodeWithTemplate(_izContext, objSchemaPath) {
478
487
  createSourceParams.push(...flowSchemaRegisters);
479
488
  }
480
489
 
481
- // console.log("createSourceParams flowSchema", createSourceParams)
490
+ console.log("createSourceParams flowSchema", createSourceParams)
482
491
  return createSourceParams;
483
492
  } catch (error) {
484
493
  _izContext.logger.error('Error generating code with template flowSchema:', error);
@@ -0,0 +1,108 @@
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 NoRetryError = require('@izara_project/izara-core-library-core').NoRetryError
21
+ const { SOURCE_PATH, SAVE_FILE_NAME, FUNCTION_NAME, HANDLER, awaitingMultipleStepsRole, resourceNames, defaultIamRolePerAction, createIamRole, RESOURCE_CLASSES, SQS_RESOURCE, DYNAMO_RESOURCE, shortNameHandler } = require('../../../../../MainLibs/src/Consts');
22
+ const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase, getLocalConfig } = require("../../../../../MainLibs/src/Utils")
23
+ const templatePath = path.join(__dirname, "./template.ejs");
24
+ const getObjectSchema = require('@izara_project/izara-core-library-service-schemas/src/GetObjectSchema');
25
+ const { STORAGE_TYPES } = require('@izara_project/izara-core-library-service-schemas/src/Consts');
26
+
27
+ /**
28
+ * receive objectSchema
29
+ *
30
+ * @param {Object} objectSchema
31
+ * @return {{templatePath, templateData,setting}}
32
+ */
33
+
34
+
35
+ async function data(_izContext, flowSchema, srcPath) {
36
+ return [await createSourceParams(_izContext, flowSchema, srcPath)]
37
+ }
38
+
39
+ async function createSourceParams(_izContext, flowSchema, srcPath) {
40
+ let functionName = "CompleteStatusField" + upperCase(flowSchema.flowTag)
41
+ let handlerType = upperCase(HANDLER.hdrSqs)
42
+ let additionalResourcePermission = defaultIamRolePerAction();
43
+ let queueName = "CompleteStatusField" + upperCase(flowSchema.flowTag) + handlerType;
44
+ let serviceTag = getLocalConfig(path.join(srcPath, "../"), "iz_serviceTag")
45
+ additionalResourcePermission.push(
46
+ createIamRole(
47
+ {
48
+ [RESOURCE_CLASSES.sqs]: Object.values(SQS_RESOURCE)
49
+ },
50
+ [
51
+ resourceNames(RESOURCE_CLASSES.sqs, queueName),
52
+ resourceNames(RESOURCE_CLASSES.sqs, queueName + "DLQ")
53
+ ]
54
+ ),
55
+ )
56
+
57
+ let tableNames = [];
58
+ let objectSchema = undefined;
59
+ if (flowSchema.objType.service === serviceTag) {
60
+ // console.log("find objSchema in Local")
61
+ objectSchema = await getObjectSchema.getLocalObjectSchemasWithHierarchy(_izContext, [flowSchema.objType.objectType], path.join(srcPath, "./schemas")).then(res => res.records[0])
62
+ } else {
63
+ // console.log("find objSchema on S3")
64
+ objectSchema = await getObjectSchema.getObjSchemaS3WithHierarchy(_izContext, flowSchema.objType)
65
+ }
66
+ if (!objectSchema) {
67
+ throw new NoRetryError('ObjectSchema not found')
68
+ }
69
+ for (const storageResource of Object.values(objectSchema.storageResources)) {
70
+ if (storageResource.storageType === STORAGE_TYPES.dynamoDB) {
71
+ if (!tableNames.includes(storageResource.tableName)) {
72
+ tableNames.push(storageResource.tableName)
73
+ }
74
+ }
75
+ }
76
+
77
+ additionalResourcePermission.push(
78
+ createIamRole(
79
+ {
80
+ [RESOURCE_CLASSES.dynamoDbTable]: Object.values(DYNAMO_RESOURCE)
81
+ },
82
+ tableNames.map(
83
+ tableName => resourceNames(RESOURCE_CLASSES.dynamoDbTable, tableName))
84
+ )
85
+ )
86
+
87
+ additionalResourcePermission.push(awaitingMultipleStepsRole())
88
+ return {
89
+ templatePath: templatePath,
90
+ templateData: {
91
+ resourceLocation: path.join(SOURCE_PATH.resourceLocationFlowSchema, upperCase(flowSchema.flowTag), "source/"),
92
+ functionName,
93
+ handlerType,
94
+ additionalResourcePermission,
95
+ functionNameConfig: upperCase(functionName) + upperCase(shortNameHandler(handlerType)),
96
+ roleName: upperCase(flowSchema.flowTag),
97
+ queueName
98
+ },
99
+ setting: {
100
+ savePath: path.join(srcPath, SOURCE_PATH.appYaml),
101
+ saveFileName: upperCase(SAVE_FILE_NAME.flowSchema),
102
+ fileExtension: ".yml",
103
+ isAppend: true
104
+ }
105
+ }
106
+ }
107
+
108
+ module.exports = data;
@@ -0,0 +1,22 @@
1
+ <%_ const join = require('path').join; _%>
2
+ <%- firstLetterUpperCase(functionNameConfig) %>:
3
+ handler: <%- join(resourceLocation, `${firstLetterUpperCase(functionName)}_${firstLetterUpperCase(handlerType)}.main`)%>
4
+ name: ${self:custom.iz_resourcePrefix}<%- firstLetterUpperCase(functionName) %><%- firstLetterUpperCase(handlerType) %>
5
+ role: <%- roleName %>Role
6
+ #<#<%- functionName %><%- handlerType %>FunctionSetting#>
7
+ #<#/<%- functionName %><%- handlerType %>FunctionSetting#>
8
+ events:
9
+ - sqs:
10
+ arn: arn:aws:sqs:${self:custom.iz_region}:${self:custom.iz_accountId}:${self:custom.iz_resourcePrefix}<%- queueName %>
11
+ batchSize: 10
12
+ filterPatterns: #**** need to update serverless framework upper v.2.69.1
13
+ - body: {"MessageAttributes":{"callingFlow":{"Value":["${self:custom.iz_resourcePrefix}<%- functionName %>"]}}} # functionName of callingFlow
14
+ - body: {"MessageAttributes":{"callingFlow":{"Value":[{"exists":false}]}}}
15
+
16
+
17
+ <%_ function firstLetterUpperCase(text){
18
+ return text.charAt(0).toUpperCase() + text.slice(1)
19
+ } _%>
20
+ <%_ function firstLetterLowerCase(str) {
21
+ return str.charAt(0).toLowerCase() + str.slice(1)
22
+ } _%>
@@ -0,0 +1,63 @@
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 NoRetryError = require('@izara_project/izara-core-library-core').NoRetryError
21
+ const { SOURCE_PATH, SAVE_FILE_NAME, FUNCTION_NAME, HANDLER, awaitingMultipleStepsRole, resourceNames, defaultIamRolePerAction, createIamRole, RESOURCE_CLASSES, SQS_RESOURCE, DYNAMO_RESOURCE, shortNameHandler } = require('../../../../../MainLibs/src/Consts');
22
+ const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase, getLocalConfig } = require("../../../../../MainLibs/src/Utils")
23
+ const templatePath = path.join(__dirname, "./template.ejs");
24
+ const getObjectSchema = require('@izara_project/izara-core-library-service-schemas/src/GetObjectSchema');
25
+ const { STORAGE_TYPES } = require('@izara_project/izara-core-library-service-schemas/src/Consts');
26
+
27
+ /**
28
+ * receive objectSchema
29
+ *
30
+ * @param {Object} objectSchema
31
+ * @return {{templatePath, templateData,setting}}
32
+ */
33
+
34
+
35
+ async function data(_izContext, flowSchema, srcPath) {
36
+ return [await createSourceParams(_izContext, flowSchema, srcPath)]
37
+ }
38
+
39
+ async function createSourceParams(_izContext, flowSchema, srcPath) {
40
+ let functionName = "CompleteStatusField" + upperCase(flowSchema.flowTag)
41
+ let handlerType = upperCase(HANDLER.hdrSqs)
42
+ let additionalResourcePermission = defaultIamRolePerAction();
43
+ let queueName = functionName + handlerType;
44
+
45
+
46
+ additionalResourcePermission.push(awaitingMultipleStepsRole())
47
+ return {
48
+ templatePath: templatePath,
49
+ templateData: {
50
+ functionName,
51
+ handlerType,
52
+ queueName
53
+ },
54
+ setting: {
55
+ savePath: path.join(srcPath, SOURCE_PATH.flowSchema, upperCase(flowSchema.flowTag), "source/"),
56
+ saveFileName: `${functionName}_${handlerType}`,
57
+ fileExtension: ".js",
58
+ isAppend: true
59
+ }
60
+ }
61
+ }
62
+
63
+ module.exports = data;
@@ -0,0 +1,85 @@
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
+
20
+ // const AWS = require('aws-sdk');
21
+ // const sqs = new AWS.SQS({ apiVersion: '2012-11-05' });
22
+
23
+ const izara = require("@izara_project/izara-middleware");
24
+ const middleware = izara.middlewareHandler;
25
+ const recordHandlerSharedLib = require("@izara_project/izara-core-library-record-handler")
26
+ const Logger = require('@izara_project/izara-core-library-logger');
27
+
28
+ const <%- functionName %> = require('./<%- functionName %>_Main')
29
+
30
+ // validate event properties in body.Message of sqs event
31
+ let perRecordsValidatorSchema = {}
32
+ middleware.setValidatorSchema(recordHandlerSharedLib.baseValidatorSchema());
33
+
34
+ module.exports.main = middleware.wrap(async (event, context, callback) => {
35
+
36
+ try {
37
+
38
+ let recordPromises = [];
39
+
40
+ // loop each record and send to mainFunction
41
+ await Promise.all(event.Records.map(async record => { // promise.all for map() function
42
+
43
+ let passOnProperties = []
44
+ record._izContext.logger.debug('record ReceiveMsgOutHdrSqs', record);
45
+
46
+ //validate message (and MessageAttributes)
47
+ await recordHandlerSharedLib.validateRecord(
48
+ record, // one record will send to mainFunction
49
+ "<%- queueName %>", // queue name that need to retry or send to dlq
50
+ perRecordsValidatorSchema, // schema for record.Message
51
+ // messageAttributeValidatorSchema // ----- for msgAttr default is null -> do not send this parameter if not want to validate msgAtt
52
+ );
53
+
54
+ // add argument (to invoke lambda) to passOnProperties[]
55
+ passOnProperties.push(record.body.Message)
56
+ record._izContext.logger.debug('passOnProperties in handler', passOnProperties);
57
+
58
+ // call recordHandlerSharedLib.recordHandler with 3 parameters and return promise(resolve)
59
+ let recordPromise = recordHandlerSharedLib.recordHandler(
60
+ record, // one record will send to mainFunction
61
+ <%- functionName %>.<%- functionName %>, // mainFunction that need to invoke.
62
+ "<%- queueName %>", // queue name that need to retry or send to dlq
63
+ passOnProperties, // all parameters that mainFunction needed.
64
+ );
65
+ record._izContext.logger.debug('after recordPromise in handler');
66
+ recordPromises.push(recordPromise); // push promise to recordPromises
67
+ }))
68
+
69
+ Logger.debug('before Promise.all(recordPromises) in handler');
70
+ try {
71
+ // --- main await all promises
72
+ await Promise.all(recordPromises); // await all promises
73
+
74
+ return event.Records // return all for local testing
75
+
76
+ } catch {
77
+ Logger.debug('Promise.all(recordPromises) in handler threw error (at least one record did no resolve)');
78
+ }
79
+ Logger.debug('after Promise.all(recordPromises) in handler');
80
+
81
+ } catch (err) {
82
+ Logger.error('Unhandled Error, <%- functionName %>: ', err);
83
+ throw (err);
84
+ }
85
+ });
@@ -0,0 +1,55 @@
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 NoRetryError = require('@izara_project/izara-core-library-core').NoRetryError
21
+ const { SOURCE_PATH } = require('../../../../../MainLibs/src/Consts');
22
+ const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase } = require("../../../../../MainLibs/src/Utils")
23
+ const templatePath = path.join(__dirname, "./template.ejs");
24
+
25
+ /**
26
+ * receive objectSchema
27
+ *
28
+ * @param {Object} objectSchema
29
+ * @return {{templatePath, templateData,setting}}
30
+ */
31
+
32
+
33
+ async function data(_izContext, flowSchema, srcPath) {
34
+ return [await createSourceParams(_izContext, flowSchema, srcPath)]
35
+ }
36
+
37
+ async function createSourceParams(_izContext, flowSchema, srcPath) {
38
+ let functionName = "CompleteStatusField" + upperCase(flowSchema.flowTag)
39
+
40
+ return {
41
+ templatePath: templatePath,
42
+ templateData: {
43
+ functionName,
44
+ flowType: flowSchema.flowTag
45
+ },
46
+ setting: {
47
+ savePath: path.join(srcPath, SOURCE_PATH.flowSchema, upperCase(flowSchema.flowTag), "source/"),
48
+ saveFileName: `${functionName}_Main`,
49
+ fileExtension: ".js",
50
+ isAppend: true
51
+ }
52
+ }
53
+ }
54
+
55
+ module.exports = data;
@@ -0,0 +1,87 @@
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
+ const getObjectSchema = require('@izara_project/izara-core-library-service-schemas/src/GetObjectSchema');
21
+ const dynamodbSharedLib = require('@izara_project/izara-core-library-dynamodb');
22
+ const snsSharedLib = require('@izara_project/izara-core-library-sns');
23
+ const sqsSharedLib = require('@izara_project/izara-core-library-sqs');
24
+ const asyncFlowSharedLib = require('@izara_project/izara-core-library-asynchronous-flow');
25
+ const callingFlowSharedLib = require('@izara_project/izara-core-library-calling-flow');
26
+ const lambdaSharedLib = require('@izara_project/izara-core-library-lambda');
27
+ const externalRequest = require('@izara_project/izara-core-library-external-request');
28
+ const sns = externalRequest.sns;
29
+ const sqs = externalRequest.sqs;
30
+ const lambda = externalRequest.lambda;
31
+ const NoRetryError = require('@izara_project/izara-core-library-core').NoRetryError;
32
+ const statusFieldSharedLib = require('@izara_project/izara-core-library-status-field');
33
+ const { createFlowTypeConcat } = require('@izara_project/izara-core-library-service-schemas').utils;
34
+
35
+ //(<optionalRequire>)
36
+ //(</optionalRequire>)
37
+ /**
38
+ *
39
+ *
40
+ * description of function.
41
+ * @param {Object} _izContext
42
+ * @param {CorrelationIds} _izContext.correlationIds - property of _izContext
43
+ * @param {Logger} _izContext.logger - property of _izContext
44
+ * @param {Object} requestParams - request params
45
+ * @param {Object} requestParams.identifiers - identifiers for get data
46
+ * @param {Object} requestParams.additionalRequest - additionalRequest
47
+ *
48
+ *
49
+ * @returns {object} description of return value
50
+ */
51
+ module.exports.<%- functionName %> = async (
52
+ _izContext,
53
+ identifiers,
54
+ statusField,
55
+ errorsFound,
56
+ //(<additionalParams>)
57
+ //(</additionalParams>)
58
+ callingFlowConfig = {},
59
+ ) => {
60
+
61
+ try {
62
+ _izContext.logger.debug("<%- functionName %> _izContext", _izContext)
63
+ _izContext.logger.debug("<%- functionName %> requestParams", requestParams)
64
+ _izContext.logger.debug("<%- functionName %> callingFlowConfig", callingFlowConfig)
65
+
66
+ //(<beforeCompleteStatusField>)
67
+ //(</beforeCompleteStatusField>)
68
+
69
+ await statusFieldSharedLib.completeStatusField(
70
+ _izContext,
71
+ {
72
+ flowTag:"<%- flowType %>",
73
+ serviceTag: process.env.iz_serviceTag
74
+ },
75
+ identifiers,
76
+ statusField,
77
+ errorsFound
78
+ )
79
+
80
+ //(<endpointHook>)
81
+ //(</endpointHook>)
82
+
83
+ } catch (err) {
84
+ _izContext.logger.error('error <%- functionName %>: ', err)
85
+ throw (err)
86
+ }
87
+ }
@@ -0,0 +1,61 @@
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 NoRetryError = require('@izara_project/izara-core-library-core').NoRetryError
21
+ const { SOURCE_PATH, SAVE_FILE_NAME } = require('../../../../../MainLibs/src/Consts');
22
+ const { firstLetterLowerCase: lowerCase, firstLetterUpperCase: upperCase } = require("../../../../../MainLibs/src/Utils")
23
+ const templatePath = path.join(__dirname, "./template.ejs");
24
+ /**
25
+ * receive objectSchema
26
+ *
27
+ * @param {Object} objectSchema
28
+ * @return {{templatePath, templateData,setting}}
29
+ */
30
+
31
+
32
+ async function data(_izContext, flowSchema, srcPath) {
33
+ let resultsForCreateDefaultSnsInSqs = [];
34
+ let flowTag = upperCase(flowSchema.flowTag)
35
+ // console.log("create topic by flowSteps", flowSteps)
36
+ const setting = {
37
+ initialData: "Resources:\n",
38
+ savePath: path.join(srcPath, SOURCE_PATH.resourceYaml),
39
+ saveFileName: SAVE_FILE_NAME.snsInSqsYaml,
40
+ fileExtension: ".yml",
41
+ isAppend: true
42
+ }
43
+
44
+ let generateTriggerCacheQueueNames = [
45
+ {
46
+ queueName: "CompleteStatusField" + flowTag
47
+ }
48
+ ]
49
+
50
+ for (let defaultSnsInSqsData of generateTriggerCacheQueueNames) {
51
+ resultsForCreateDefaultSnsInSqs.push({
52
+ templatePath: templatePath,
53
+ templateData: defaultSnsInSqsData,
54
+ setting: setting
55
+ })
56
+ }
57
+
58
+ return resultsForCreateDefaultSnsInSqs;
59
+ }
60
+
61
+ module.exports = data;
@@ -0,0 +1,59 @@
1
+ ##===== [Create topic in]
2
+ In<%- queueName %>:
3
+ Type: AWS::SNS::Topic
4
+ Properties:
5
+ DisplayName: "SNS Message in"
6
+ TopicName: ${self:custom.iz_serviceTag}_${self:custom.iz_stage}_<%- queueName %>_In
7
+ ##===== SNS Subscription
8
+ ##===== [Topic In]
9
+ SubscriptionIn<%- queueName %>:
10
+ Type: AWS::SNS::Subscription
11
+ Properties:
12
+ TopicArn: !Ref In<%- queueName %>
13
+ Endpoint: "arn:aws:sqs:${self:custom.iz_region}:${self:custom.iz_accountId}:${self:custom.iz_resourcePrefix}<%- queueName %>HdrSqs"
14
+ Protocol: "sqs"
15
+ ##===== [Queue]
16
+ <%- queueName %>HdrSqs:
17
+ Type: "AWS::SQS::Queue"
18
+ Properties:
19
+ QueueName: ${self:custom.iz_resourcePrefix}<%- queueName %>HdrSqs
20
+ RedrivePolicy:
21
+ deadLetterTargetArn:
22
+ # !GetAtt
23
+ Fn::GetAtt:
24
+ - <%- queueName %>HdrSqsDLQ
25
+ - Arn
26
+ maxReceiveCount: 3
27
+ VisibilityTimeout: 120
28
+ ##==== [QueueDLQ]
29
+ <%- queueName %>HdrSqsDLQ:
30
+ Type: AWS::SQS::Queue
31
+ Properties:
32
+ QueueName: ${self:custom.iz_resourcePrefix}<%- queueName %>HdrSqsDLQ
33
+ ##==== [QueuePolicy]
34
+ <%- queueName %>HdrSqsPolicy:
35
+ Type: AWS::SQS::QueuePolicy
36
+ Properties:
37
+ PolicyDocument:
38
+ Version: "2012-10-17"
39
+ Statement:
40
+ - Sid: "allow-sns-messages"
41
+ Effect: Allow
42
+ Principal: "*"
43
+ Resource:
44
+ # !GetAtt
45
+ Fn::GetAtt:
46
+ - <%- queueName %>HdrSqs
47
+ - Arn
48
+ Action: "SQS:SendMessage"
49
+ Queues:
50
+ - Ref: <%- queueName %>HdrSqs
51
+ #<#<%- firstLetterUpperCase(queueName) %>QueueSetting#>
52
+ #<#/<%- firstLetterUpperCase(queueName) %>QueueSetting#>
53
+
54
+ <%_ function firstLetterUpperCase(text){
55
+ return text.charAt(0).toUpperCase() + text.slice(1)
56
+ } _%>
57
+ <%_ function firstLetterLowerCase(str) {
58
+ return str.charAt(0).toLowerCase() + str.slice(1)
59
+ } _%>
@@ -1,22 +1,29 @@
1
- // getObjectSchema
2
- let objectSchema = await getObjectSchema.getObjSchemaS3WithCache(_izContext, flowSchema.objType)
1
+ //(<beforeCheckedStatusField>)
2
+ //(</beforeCheckedStatusField>)
3
3
 
4
- // create record
5
- let fieldNames = createFieldNamesFromRequestParamsByObjectSchema(_izContext, requestParams, objectSchema)
6
-
7
- let payload = {
8
- fieldNames
9
- }
10
- Object.assign(payload, {
11
- objectType: flowSchema.objType.objectType
12
- })
13
-
14
- let result = await lambda.invokeSync(_izContext,
15
- await lambdaSharedLib.lambdaFunctionName(_izContext, "CreateHdrInv", flowSchema.objType.serviceTag),
4
+ let [ status, flowStatusFieldRecord] = await statusFieldSharedLib.checkStatusField(
5
+ _izContext,
6
+ {
7
+ flowTag: "<%- flowTag %>",
8
+ serviceTag: process.env.iz_serviceTag
9
+ },
16
10
  {
17
- payload: JSON.stringify(payload)
18
- });
11
+ //(<identifiers>)
12
+ //(</identifiers>)
13
+ },
14
+ //(<overwriteUniqueRequestId>)
15
+ //(</overwriteUniqueRequestId>)
16
+ )
19
17
 
20
- _izContext.logger.debug("result from createRecordByStatusType", result)
18
+ //(<afterCheckStatusField>)
19
+ //(</afterCheckStatusField>)
21
20
 
21
+ if (status !== "process") {
22
+ if (status === "error" || status === "complete") {
23
+ //(<afterValidateStatusField>)
24
+ //(</afterValidateStatusField>)
25
+ }
22
26
 
27
+ //(<checkStatusFieldHook>)
28
+ //(</checkStatusFieldHook>)
29
+ }