vtlab-generic-functions 1.0.4

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.
@@ -0,0 +1,164 @@
1
+ let GLOBAL_MYSQL_LIMIT = 10;
2
+ let GLOBAL_MYSQL_OFFSET = 0;
3
+
4
+ /**
5
+ * To build LIMIT query, 10 is the default limit
6
+ * @param limit
7
+ * @returns {string}
8
+ */
9
+ const buildLimitQuery = (limit) => {
10
+ let limitQuery = '';
11
+ if (limit.length > 0) {
12
+ limitQuery += ` LIMIT ${limit}`;
13
+ } else {
14
+ limitQuery += ` LIMIT ${GLOBAL_MYSQL_LIMIT}`;
15
+ }
16
+ return limitQuery;
17
+ };
18
+
19
+ /**
20
+ * To build WHERE query
21
+ * @param where
22
+ * @returns {string}
23
+ */
24
+ const buildWhereQuery = (where) => {
25
+ let whereQuery = '';
26
+ if (where.length > 0) {
27
+ where.forEach((item, index) => {
28
+ if (index === 0) {
29
+ whereQuery += ` WHERE ${item.column} ${item.operator} ${item.value}`;
30
+ } else {
31
+ whereQuery += ` AND ${item.column} ${item.operator} ${item.value}`;
32
+ }
33
+ });
34
+ }
35
+ return whereQuery;
36
+ };
37
+
38
+ /**
39
+ * To build OFFSET query
40
+ * @param offset
41
+ * @returns {string}
42
+ */
43
+ const buildOffsetQuery = (offset) => {
44
+ let offsetQuery = '';
45
+ if (offset.length > 0) {
46
+ offsetQuery += ` OFFSET ${offset}`;
47
+ } else {
48
+ offsetQuery += ` OFFSET ${GLOBAL_MYSQL_OFFSET}`;
49
+ }
50
+ return offsetQuery;
51
+ };
52
+
53
+ /**
54
+ * To build ORDER BY query
55
+ * @param orderBy
56
+ * @returns {string}
57
+ */
58
+ const buildOrderByQuery = (orderBy) => {
59
+ let orderByQuery = '';
60
+ if (orderBy.length > 0) {
61
+ orderBy.forEach((item, index) => {
62
+ if (index === 0) {
63
+ orderByQuery += ` ORDER BY ${item.key} ${item.order}`;
64
+ } else {
65
+ orderByQuery += `, ${item.key} ${item.order}`;
66
+ }
67
+ });
68
+ }
69
+ return orderByQuery;
70
+ };
71
+
72
+ /**
73
+ * To build INSERT query
74
+ * @param tableName
75
+ * @param data
76
+ * @returns {string}
77
+ */
78
+ const buildInsertQuery = (tableName, data) => {
79
+ let insertQuery = `INSERT INTO \`${tableName}\``;
80
+ let keys = Object.keys(data);
81
+ let values = keys.map(key => data[key]);
82
+ insertQuery += `(${keys.join(', ')}) VALUES (${values.join(', ')})`;
83
+ return insertQuery;
84
+ };
85
+
86
+ /**
87
+ * To build UPDATE Query
88
+ * @param tableName
89
+ * @param data
90
+ * @param where
91
+ * @returns {string}
92
+ */
93
+ const buildUpdateQuery = (tableName, data, where) => {
94
+
95
+ let updateQuery = `UPDATE \`${tableName}\` SET`;
96
+ let keys = Object.keys(data);
97
+ let values = keys.map(key => data[key]);
98
+ keys.forEach((key, index) => {
99
+ if (index === 0) {
100
+ updateQuery += ` ${key} = ${values[index]}`;
101
+ } else {
102
+ updateQuery += `, ${key} = ${values[index]}`;
103
+ }
104
+ });
105
+ updateQuery += buildWhereQuery(where);
106
+ return updateQuery;
107
+ };
108
+
109
+ /**
110
+ * to build DELETE query
111
+ * @param tableName
112
+ * @param where
113
+ * @returns {string}
114
+ */
115
+ const buildDeleteQuery = (tableName, where) => {
116
+ let deleteQuery = `DELETE FROM \`${tableName}\``;
117
+ deleteQuery += buildWhereQuery(where);
118
+ return deleteQuery;
119
+ };
120
+
121
+ /**
122
+ * to build SELECT query
123
+ * @param tableName
124
+ * @param where
125
+ * @param orderBy
126
+ * @param limit
127
+ * @param offset
128
+ * @returns {string}
129
+ */
130
+ const buildSelectQuery = (tableName = '', where = [], orderBy = [], limit = GLOBAL_MYSQL_LIMIT, offset = GLOBAL_MYSQL_OFFSET) => {
131
+ let selectQuery = `SELECT * FROM \`${tableName}\``;
132
+ selectQuery += buildWhereQuery(where);
133
+ selectQuery += buildOrderByQuery(orderBy);
134
+ selectQuery += buildLimitQuery(limit);
135
+ selectQuery += buildOffsetQuery(offset);
136
+ return selectQuery;
137
+ };
138
+
139
+ /**
140
+ * to build create table query
141
+ * @param tableName
142
+ * @param columns
143
+ * @returns {string}
144
+ */
145
+ const buildCreateTableQuery = (tableName, columns) => {
146
+ let createTableQuery = `CREATE TABLE \`${tableName}\` (`;
147
+ let keys = Object.keys(columns);
148
+ let values = keys.map(key => columns[key]);
149
+ createTableQuery += `${keys.join(', ')}`;
150
+ createTableQuery += `) ENGINE=InnoDB DEFAULT CHARSET=utf8;`;
151
+ return createTableQuery;
152
+ };
153
+
154
+
155
+ module.exports = {
156
+ buildLimitQuery,
157
+ buildWhereQuery,
158
+ buildOffsetQuery,
159
+ buildOrderByQuery,
160
+ buildInsertQuery,
161
+ buildUpdateQuery,
162
+ buildDeleteQuery,
163
+ buildSelectQuery
164
+ };
@@ -0,0 +1,175 @@
1
+ const { S3Client, PutObjectCommand, GetObjectCommand, getSignedUrl } = require("@aws-sdk/client-s3");
2
+ const config = require('../config');
3
+ const multer = require('multer');
4
+ const multerS3 = require('multer-s3');
5
+ const { promisesCollector } = require('../utils');
6
+
7
+ /**
8
+ * Uploads a file to an S3 bucket.
9
+ *
10
+ * @param {string} path - The path (including the file name) where the file will be stored in the bucket.
11
+ * @param {Buffer|string} file - The file data to upload. Can be a Buffer or a string.
12
+ * @param {Object} options - Additional options for the S3 upload (e.g., ACL, ContentType).
13
+ * @param {string} [bucketName="s3bucket"] - The name of the S3 bucket on the config. Defaults to 's3bucket'.
14
+ * @returns {Promise<string>} - A promise that resolves to the path of the uploaded file.
15
+ * @throws {Error} - Throws an error if the upload fails.
16
+ */
17
+ const uploadToS3 = async (path, file, options, bucketName = "s3bucket") => {
18
+ try {
19
+ const allConfig = await config.get();
20
+ const bucket = allConfig[bucketName];
21
+ if (!bucket) {
22
+ throw new Error(`Bucket ${bucketName} not found in config`);
23
+ }
24
+
25
+ const s3Client = new S3Client({
26
+ credentials: {
27
+ accessKeyId: allConfig.awsCredentials.accessKeyId,
28
+ secretAccessKey: allConfig.awsCredentials.secretAccessKey,
29
+ },
30
+ region: allConfig.awsCredentials.region,
31
+ });
32
+
33
+ const command = new PutObjectCommand({
34
+ Bucket: bucket,
35
+ Key: path,
36
+ Body: file,
37
+ ACL: 'public-read',
38
+ ...options
39
+ });
40
+
41
+ await s3Client.send(command);
42
+ return path;
43
+ } catch (error) {
44
+ throw error;
45
+ }
46
+ };
47
+
48
+ /**
49
+ * Creates a multer instance configured to upload files to an S3 bucket.
50
+ *
51
+ * @returns {Promise<Multer>} - A promise that resolves to a Multer instance.
52
+ * @throws {Error} - Throws an error if the configuration fails.
53
+ */
54
+ const uploadMultiForm = async () => {
55
+ const allConfig = await config.get();
56
+ const s3Client = new S3Client({
57
+ credentials: {
58
+ accessKeyId: allConfig.awsCredentials.accessKeyId,
59
+ secretAccessKey: allConfig.awsCredentials.secretAccessKey,
60
+ },
61
+ region: allConfig.awsCredentials.region
62
+ });
63
+
64
+ return multer({
65
+ storage: multerS3({
66
+ s3: s3Client,
67
+ bucket: allConfig.s3bucket,
68
+ acl: 'private',
69
+ metadata: (req, file, cb) => {
70
+ cb(null, { fieldName: file.fieldname });
71
+ },
72
+ key: (req, file, cb) => {
73
+ const url = `${req.internalParams.filesUrl}/${file.originalname}`;
74
+ cb(null, url);
75
+ }
76
+ }),
77
+ limits: {
78
+ fileSize: 50 * 1024 * 1024, // 50 MB
79
+ fields: 20,
80
+ parts: 100,
81
+ },
82
+ });
83
+ };
84
+
85
+ /**
86
+ * Downloads a file from an S3 bucket.
87
+ *
88
+ * @param {string} path - The path (including the file name) of the file in the S3 bucket.
89
+ * @returns {Promise<Object>} - A promise that resolves to the downloaded file data.
90
+ * @throws {Error} - Throws an error if the download fails.
91
+ */
92
+ const downloadFileFromS3 = async (path) => {
93
+ try {
94
+ const allConfig = await config.get();
95
+ const s3Client = new S3Client({
96
+ credentials: {
97
+ accessKeyId: allConfig.awsCredentials.accessKeyId,
98
+ secretAccessKey: allConfig.awsCredentials.secretAccessKey,
99
+ },
100
+ region: allConfig.awsCredentials.region
101
+ });
102
+
103
+ const command = new GetObjectCommand({
104
+ Bucket: allConfig.s3bucket,
105
+ Key: path
106
+ });
107
+
108
+ const data = await s3Client.send(command);
109
+ return data;
110
+ } catch (error) {
111
+ throw error;
112
+ }
113
+ };
114
+
115
+ /**
116
+ * Uploads multiple files to an S3 bucket.
117
+ *
118
+ * @param {string} path - The base path where the files will be stored in the bucket.
119
+ * @param {Array<Object>} files - An array of file objects to upload.
120
+ * @param {string} [extension='pdf'] - The extension to append to each file.
121
+ * @param {Object} [options={}] - Default options for each file upload.
122
+ * @returns {Promise<Array<string>>} - A promise that resolves to an array of paths of the uploaded files.
123
+ * @throws {Error} - Throws an error if the upload fails.
124
+ */
125
+ const uploadFilesToS3 = async (path, files, extension = 'pdf', options = {
126
+ ACL: "private",
127
+ ContentEncoding: "base64",
128
+ ContentType: "application/pdf",
129
+ }) => {
130
+ if (files.length === 0 || !path) {
131
+ return "";
132
+ }
133
+
134
+ return promisesCollector(files, async (_file) => {
135
+ let _path = `${path}${new Date().getTime()}.${extension}`;
136
+ try {
137
+ let file = Buffer.from(_file.content, "base64");
138
+ return uploadToS3(_path, file, options);
139
+ } catch (error) {
140
+ throw new Error("Error creating file in AWS");
141
+ }
142
+ });
143
+ };
144
+
145
+ /**
146
+ * Generates a presigned URL for a file stored in an S3 bucket.
147
+ *
148
+ * @param {string} bucket - The name of the S3 bucket.
149
+ * @param {string} key - The key of the file in the S3 bucket.
150
+ * @param {number} [expirationInSeconds=2592000] - The expiration time of the URL in seconds. Defaults to 30 days.
151
+ * @returns {Promise<string>} - A promise that resolves to the presigned URL.
152
+ * @throws {Error} - Throws an error if the URL generation fails.
153
+ */
154
+ const generatePresignedUrl = async (bucket, key, expirationInSeconds = 86400 * 30) => {
155
+ try {
156
+ const s3Client = new S3Client();
157
+
158
+ const command = new GetObjectCommand({
159
+ Bucket: bucket,
160
+ Key: key,
161
+ });
162
+
163
+ return await getSignedUrl(s3Client, command, { expiresIn: expirationInSeconds });
164
+ } catch (error) {
165
+ throw error;
166
+ }
167
+ };
168
+
169
+ module.exports = {
170
+ uploadToS3,
171
+ downloadFileFromS3,
172
+ uploadMultiForm,
173
+ uploadFilesToS3,
174
+ generatePresignedUrl
175
+ };
package/soap/index.js ADDED
@@ -0,0 +1,71 @@
1
+ const soapRequest = require('easy-soap-request');
2
+ var xml2js = require('xml2js');
3
+
4
+
5
+ /**
6
+ * Private fucntions
7
+ */
8
+
9
+
10
+
11
+
12
+ /**
13
+ * API functions
14
+ */
15
+
16
+ /**
17
+ * This function will send a SOAP Request
18
+ * @param {string} url
19
+ * @param {string} headers {'user-agent': '' , 'Content-type': '', 'soapAction': ''}
20
+ * @param {string} xml
21
+ * @param {int} timeout
22
+ * @returns {Promise} {
23
+ * headers,
24
+ * body,
25
+ * statusCode
26
+ * }
27
+ * @throw error: If validate method fails.
28
+ */
29
+ const sendSoapRequest = async ({url, headers, xml, timeout=3000 }) => {
30
+ try{
31
+ let {response} = await soapRequest({ url: url, headers: headers, xml: xml, timeout});
32
+ return response; //{ headers, body, statusCode }
33
+ }catch(err){
34
+ throw err;
35
+ }
36
+ }
37
+
38
+ const getSoapHeaders = ({contentType='text/xml;charset=UTF-8', soapAction, userAgent}) =>{
39
+ let headers= {}
40
+ headers['Content-type'] = contentType;
41
+ if(soapAction) headers['SOAPAction'] = soapAction;
42
+ if (userAgent) headers['user-agent'] = userAgent;
43
+ return headers;
44
+ }
45
+
46
+ const xmlToJson = async (dataXml, options) =>{
47
+ try{
48
+ let jsonRes = xml2js.parseStringPromise(dataXml,options);
49
+ return jsonRes;
50
+ }catch(err){
51
+ throw err;
52
+ }
53
+ }
54
+
55
+ const jsonToXml = async (dataJson,options) =>{
56
+ try{
57
+ let builder = new xml2js.Builder();
58
+ let xmlRes = builder.buildObject(dataJson);
59
+ return xmlRes;
60
+ }catch(err){
61
+ throw err
62
+ }
63
+ }
64
+
65
+
66
+ module.exports = {
67
+ sendSoapRequest,
68
+ getSoapHeaders,
69
+ xmlToJson,
70
+ jsonToXml
71
+ }
package/sqs/index.js ADDED
@@ -0,0 +1,85 @@
1
+ const { SQSClient, SendMessageCommand } = require("@aws-sdk/client-sqs");
2
+ const config = require('../config');
3
+ const validator = require('../validator');
4
+
5
+ /**
6
+ * Sends a message to an SQS queue.
7
+ *
8
+ * @param {Object} message - The message to be sent to the queue.
9
+ * @param {string} queueUrl - The URL of the SQS queue.
10
+ * @param {boolean} [isFIFOQueue=true] - Specifies if the queue is a FIFO queue.
11
+ * @returns {Promise<Object>} - A promise that resolves to the response from SQS.
12
+ * @throws {Error} - Throws an error if sending the message fails.
13
+ */
14
+ const sendSQSMessage = async (message, queueUrl, isFIFOQueue = true) => {
15
+ try {
16
+ const awsCredentials = await config.get('awsCredentials');
17
+ const environment = process.env.NODE_ENV || 'develop';
18
+
19
+ const sqsClient = new SQSClient({
20
+ region: awsCredentials.region,
21
+ credentials: {
22
+ accessKeyId: awsCredentials.accessKeyId,
23
+ secretAccessKey: awsCredentials.secretAccessKey
24
+ }
25
+ });
26
+
27
+ const params = {
28
+ MessageBody: JSON.stringify(message),
29
+ QueueUrl: queueUrl,
30
+ };
31
+
32
+ if (isFIFOQueue) {
33
+ params.MessageGroupId = environment;
34
+ }
35
+
36
+ const command = new SendMessageCommand(params);
37
+ const data = await sqsClient.send(command);
38
+ return data;
39
+ } catch (error) {
40
+ throw error;
41
+ }
42
+ };
43
+
44
+ /**
45
+ * Saves a job event to an SQS queue.
46
+ *
47
+ * @param {Object} [document={}] - The job event document to be saved.
48
+ * @returns {Promise<Object>} - A promise that resolves to the response from SQS.
49
+ * @throws {Error} - Throws an error if saving the job event fails.
50
+ */
51
+ const saveJobEvent = async (document = {}) => {
52
+ try {
53
+ const jobEvent = validator.validate(document, 'jobEvent');
54
+ const queue = await config.get('microservices.sqs.jobEvent');
55
+ const environment = process.env.NODE_ENV || 'develop';
56
+
57
+ return sendSQSMessage({ document: jobEvent, environment }, queue);
58
+ } catch (error) {
59
+ throw error;
60
+ }
61
+ };
62
+
63
+ /**
64
+ * Saves an integration message to an SQS queue.
65
+ *
66
+ * @param {Object} [document={}] - The integration message document to be saved.
67
+ * @returns {Promise<Object>} - A promise that resolves to the response from SQS.
68
+ * @throws {Error} - Throws an error if saving the integration message fails.
69
+ */
70
+ const saveIntegrationMessages = async (document = {}) => {
71
+ try {
72
+ const integrationMessages = validator.validate(document, 'integrationMessages');
73
+ const queue = await config.get('microservices.sqs.integrationMessage');
74
+ const environment = process.env.NODE_ENV || 'develop';
75
+
76
+ return sendSQSMessage(integrationMessages, queue, false);
77
+ } catch (error) {
78
+ throw error;
79
+ }
80
+ };
81
+
82
+ module.exports = {
83
+ saveJobEvent,
84
+ saveIntegrationMessages
85
+ };