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.
- package/axios/README.md +30 -0
- package/axios/index.js +287 -0
- package/axios/logs.js +110 -0
- package/axios/utils.js +37 -0
- package/cloudwatch/index.js +109 -0
- package/config/index.js +74 -0
- package/customers/marketplace/bringg/auth.js +59 -0
- package/dataMapper/index.js +61 -0
- package/emails/index.js +153 -0
- package/ftp/ftp-promise-wrapper.js +109 -0
- package/ftp/index.js +194 -0
- package/ftp/jsftp-wrapper.js +107 -0
- package/ftp/ssh2SFPTWrapper.js +175 -0
- package/geocode/README.md +18 -0
- package/geocode/index.js +28 -0
- package/lambda/index.js +68 -0
- package/lambdaClass/index.js +267 -0
- package/mongodb/README.md +16 -0
- package/mongodb/connect-to-mongodb.js +57 -0
- package/mongodb/index.js +8 -0
- package/mongodb/models/users.js +51 -0
- package/mysql/README.md +29 -0
- package/mysql/connect-to-mysqldb.js +26 -0
- package/mysql/index.js +8 -0
- package/mysql/models/users.js +47 -0
- package/mysql/utils/queryBuilder.js +164 -0
- package/package.json +43 -0
- package/parsingFiles/index.js +114 -0
- package/pdf/index.js +34 -0
- package/postalCode/index.js +38 -0
- package/rds/connect-to-rdsdb.js +33 -0
- package/rds/index.js +33 -0
- package/rds/utils/queryBuilder.js +164 -0
- package/s3bucket/index.js +175 -0
- package/soap/index.js +71 -0
- package/sqs/index.js +85 -0
- package/utils/index.js +579 -0
- package/validator/index.js +44 -0
- package/validator/joiSchema.js +311 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
var Client = require('ssh2').Client
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* List all files inside sftp for a certain path
|
|
5
|
+
* @param {object} config the configuration including host user port and password
|
|
6
|
+
* @param {string} path the path to retrieve the list from
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const listDirectory = (config, path = '.') => {
|
|
10
|
+
return new Promise((resolve, reject) => {
|
|
11
|
+
const conn = new Client();
|
|
12
|
+
const connSettings = {
|
|
13
|
+
host: config.host,
|
|
14
|
+
username: config.user,
|
|
15
|
+
tryKeyboard: true,
|
|
16
|
+
port: config.port,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
conn.on('ready', function () {
|
|
20
|
+
conn.sftp(function (err, sftp) {
|
|
21
|
+
if (err) reject(err);
|
|
22
|
+
sftp.readdir(path, function (err, list) {
|
|
23
|
+
if (err) {
|
|
24
|
+
reject(err)
|
|
25
|
+
}
|
|
26
|
+
conn.end();
|
|
27
|
+
resolve(list)
|
|
28
|
+
})
|
|
29
|
+
});
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
conn.on('keyboard-interactive', function (name, instr, lang, prompts, cb) {
|
|
33
|
+
console.log("keyboard-interactive");
|
|
34
|
+
cb([config.password]);
|
|
35
|
+
}).connect(connSettings);
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Writes a file in the desired path
|
|
41
|
+
* @param {object} config the configuration including host user port and password
|
|
42
|
+
* @param {string} path the path to save the file
|
|
43
|
+
* @param {object} content a buffer of the data to write
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
const writeFile = (config, path, content) => {
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
const conn = new Client();
|
|
49
|
+
const connSettings = {
|
|
50
|
+
host: config.host,
|
|
51
|
+
username: config.user,
|
|
52
|
+
tryKeyboard: true,
|
|
53
|
+
port: config.port,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
conn.on('ready', function () {
|
|
57
|
+
conn.sftp(function (err, sftp) {
|
|
58
|
+
if (err) reject(err);
|
|
59
|
+
const writeStream = sftp.createWriteStream(path);
|
|
60
|
+
const data = writeStream.end(content);
|
|
61
|
+
writeStream.on('close', function() {
|
|
62
|
+
console.log("- file transferred succesfully");
|
|
63
|
+
resolve(data);
|
|
64
|
+
conn.end();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
conn.on('keyboard-interactive', function (name, instr, lang, prompts, cb) {
|
|
70
|
+
console.log("keyboard-interactive");
|
|
71
|
+
cb([config.password]);
|
|
72
|
+
}).connect(connSettings);
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Deletes a file from the sftp
|
|
78
|
+
* @param {object} config the configuration including host user port and password
|
|
79
|
+
* @param {string} path the path to delete the file
|
|
80
|
+
*/
|
|
81
|
+
|
|
82
|
+
const deleteFile = (config, path) => {
|
|
83
|
+
return new Promise((resolve, reject) => {
|
|
84
|
+
const conn = new Client();
|
|
85
|
+
const connSettings = {
|
|
86
|
+
host: config.host,
|
|
87
|
+
username: config.user,
|
|
88
|
+
tryKeyboard: true,
|
|
89
|
+
port: config.port,
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
conn.on('ready', function () {
|
|
93
|
+
conn.sftp(function (err, sftp) {
|
|
94
|
+
if (err) reject(err);
|
|
95
|
+
sftp.unlink(path, function(err) {
|
|
96
|
+
if (err) {
|
|
97
|
+
console.log("Error in removing directory", err);
|
|
98
|
+
conn.end();
|
|
99
|
+
reject(err);
|
|
100
|
+
} else {
|
|
101
|
+
console.log("Directory remove from server");
|
|
102
|
+
conn.end();
|
|
103
|
+
resolve("deleted");
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
});
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
conn.on('keyboard-interactive', function (name, instr, lang, prompts, cb) {
|
|
111
|
+
console.log("keyboard-interactive");
|
|
112
|
+
cb([config.password]);
|
|
113
|
+
}).connect(connSettings);
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Retrieves a file in the desired path. Returns a buffer, use toString
|
|
119
|
+
* @param {object} config the configuration including host user port and password
|
|
120
|
+
* @param {string} path the path to get the file
|
|
121
|
+
*/
|
|
122
|
+
|
|
123
|
+
const getFile = (config, path) => {
|
|
124
|
+
return new Promise((resolve, reject) => {
|
|
125
|
+
const conn = new Client();
|
|
126
|
+
const connSettings = {
|
|
127
|
+
host: config.host,
|
|
128
|
+
username: config.user,
|
|
129
|
+
tryKeyboard: true,
|
|
130
|
+
port: config.port,
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
let localFile;
|
|
134
|
+
|
|
135
|
+
conn.on('ready', function () {
|
|
136
|
+
conn.sftp(function (err, sftp) {
|
|
137
|
+
if (err) reject(err);
|
|
138
|
+
sftp.readFile(path, function(err, file) {
|
|
139
|
+
if (err) {
|
|
140
|
+
console.log("Error on listing directory", err);
|
|
141
|
+
reject(err);
|
|
142
|
+
} else {
|
|
143
|
+
localFile = file;
|
|
144
|
+
conn.end();
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
});
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
conn.on('close', function() {
|
|
152
|
+
if (localFile) {
|
|
153
|
+
resolve(localFile);
|
|
154
|
+
}
|
|
155
|
+
reject("Error on retrieving single file");
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
conn.on('error', function() {
|
|
159
|
+
reject("Error on retrieving single file");
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
conn.on('keyboard-interactive', function (name, instr, lang, prompts, cb) {
|
|
163
|
+
console.log("keyboard-interactive");
|
|
164
|
+
cb([config.password]);
|
|
165
|
+
}).connect(connSettings);
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
module.exports = {
|
|
171
|
+
listDirectory,
|
|
172
|
+
writeFile,
|
|
173
|
+
deleteFile,
|
|
174
|
+
getFile
|
|
175
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
### Example usage from Lambda JS:
|
|
2
|
+
|
|
3
|
+
```javascript
|
|
4
|
+
|
|
5
|
+
try {
|
|
6
|
+
|
|
7
|
+
let result = await geocode.getCoordinates({
|
|
8
|
+
"logId": "apiGateway/microservices",
|
|
9
|
+
"payload": []
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
console.log(result.data);
|
|
14
|
+
|
|
15
|
+
} catch (error) {
|
|
16
|
+
console.log('ERROR', error);
|
|
17
|
+
}
|
|
18
|
+
```
|
package/geocode/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const request = require('../axios');
|
|
2
|
+
const config = require('../config');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Get coordinates from PEL backend
|
|
6
|
+
* @param params
|
|
7
|
+
* @returns {Promise<unknown>}
|
|
8
|
+
*/
|
|
9
|
+
exports.getCoordinates = async (params) => {
|
|
10
|
+
return new Promise(async (resolve, reject) => {
|
|
11
|
+
try {
|
|
12
|
+
|
|
13
|
+
let geoConfig = await config.get('geocode');
|
|
14
|
+
let url = `${geoConfig.url}`;
|
|
15
|
+
let result = await request.get(url, {
|
|
16
|
+
'auth': geoConfig.auth, // from secret manager
|
|
17
|
+
'logId': params.logId // from lambda function
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
// return result
|
|
21
|
+
resolve(result);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
|
|
24
|
+
//return error
|
|
25
|
+
reject(error);
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
};
|
package/lambda/index.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Importing only the required client and commands from AWS SDK v3
|
|
2
|
+
const { LambdaClient, InvokeCommand } = require("@aws-sdk/client-lambda");
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* DEPRECATED: Invokes lambda function
|
|
6
|
+
* @param payload {Object} Input should be Object or JSON Stringified
|
|
7
|
+
* @param functionName {String} lambda function name
|
|
8
|
+
* @returns {Promise<unknown>} Returns the result of the lambda function
|
|
9
|
+
*/
|
|
10
|
+
const invoke = async (payload, functionName) => {
|
|
11
|
+
console.log("invoke function on shared layer its deprecated, use intead invokeLambda");
|
|
12
|
+
if (typeof payload === "object" && !Array.isArray(payload) && payload !== null) {
|
|
13
|
+
payload = JSON.stringify(payload);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const client = new LambdaClient({
|
|
17
|
+
maxAttempts: 3, // Max retries
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const command = new InvokeCommand({
|
|
21
|
+
FunctionName: functionName,
|
|
22
|
+
Payload: Buffer.from(payload)
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
const { Payload } = await client.send(command);
|
|
27
|
+
return JSON.parse(Payload.toString());
|
|
28
|
+
} catch (error) {
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Invokes a specified AWS Lambda function.
|
|
35
|
+
*
|
|
36
|
+
* @param {Object|string} payload - The payload to send to the Lambda function. If an object is provided, it will be stringified.
|
|
37
|
+
* @param {string} functionName - The name of the Lambda function to invoke.
|
|
38
|
+
* @param {Object} [options={}] - Optional parameters for the function invocation.
|
|
39
|
+
* @param {number} [options.timeout=900000] - The timeout in milliseconds for the Lambda function. Defaults to 900,000 (15 minutes).
|
|
40
|
+
* @param {number} [options.maxCount=2] - The maximum number of retry attempts for the Lambda function invocation. Defaults to 2.
|
|
41
|
+
* @returns {Promise<unknown>} A promise that resolves with the result of the Lambda function invocation.
|
|
42
|
+
* @throws {Error} Throws an error if the invocation fails and exceeds the maximum retry count.
|
|
43
|
+
*
|
|
44
|
+
*/
|
|
45
|
+
const invokeLambda = async (payload, functionName, options = {}) => {
|
|
46
|
+
let { timeout, maxCount } = options;
|
|
47
|
+
const client = new LambdaClient({
|
|
48
|
+
maxAttempts: maxCount || 3,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const command = new InvokeCommand({
|
|
52
|
+
FunctionName: functionName,
|
|
53
|
+
Payload: Buffer.from(payload)
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
const { Payload } = await client.send(command);
|
|
58
|
+
return JSON.parse(Payload.toString());
|
|
59
|
+
} catch (error) {
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
// Export
|
|
65
|
+
module.exports = {
|
|
66
|
+
invoke, // deprecated
|
|
67
|
+
invokeLambda
|
|
68
|
+
};
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
const cloudwatch = require("../cloudwatch");
|
|
2
|
+
const utils = require("../utils");
|
|
3
|
+
const axiosRequest = require("../axios");
|
|
4
|
+
const axios = require("axios");
|
|
5
|
+
const promiseFTPWrapper = require("../ftp/ftp-promise-wrapper");
|
|
6
|
+
const promiseFTP = require("promise-ftp");
|
|
7
|
+
const s3bucket = require("../s3bucket");
|
|
8
|
+
|
|
9
|
+
module.exports = class Lambda {
|
|
10
|
+
event;
|
|
11
|
+
logGroupName;
|
|
12
|
+
logUuid;
|
|
13
|
+
jobs;
|
|
14
|
+
auth;
|
|
15
|
+
carrier;
|
|
16
|
+
configFTP = {};
|
|
17
|
+
ftpFolders = {};
|
|
18
|
+
ftpConnection;
|
|
19
|
+
jobsByTrackingId;
|
|
20
|
+
DEBUG;
|
|
21
|
+
|
|
22
|
+
results = {
|
|
23
|
+
totalError: 0, totalSuccess: 0, error: [], success: [],
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
constructor({carrier, event, DEBUG = false}) {
|
|
27
|
+
this.DEBUG = false;
|
|
28
|
+
this.carrier = carrier;
|
|
29
|
+
if (event.body) {
|
|
30
|
+
//Locally we receive event.body, event.body needs to be parsed. In AWS all fields are into event. (event={lodId:'...', payload:[]})
|
|
31
|
+
event = JSON.parse(event.body);
|
|
32
|
+
}
|
|
33
|
+
this.event = event.body ? event.body : event;
|
|
34
|
+
|
|
35
|
+
this.logGroupName = event.logId.split(" ")[0];
|
|
36
|
+
this.logUuid = event.logId.split(" ")[1] + ": Lambda(" + Math.round(Math.random() * 10000).toString(32) + ")- ";
|
|
37
|
+
this.logStreamName = event.logId.split(" ")[2];
|
|
38
|
+
global.LOG_STREAM_NAME = event.logId.split(" ")[2];
|
|
39
|
+
|
|
40
|
+
this.env = event.auth.env || event.auth.environment || event.auth.mainEnv || process.env.NODE_ENV;
|
|
41
|
+
this.credentialsEnv = event.auth.credentialsEnv;
|
|
42
|
+
if (event.auth.ftp) this.ftpSettings = event.auth.ftp;
|
|
43
|
+
|
|
44
|
+
process.env.NODE_ENV = this.env;
|
|
45
|
+
|
|
46
|
+
this.jobs = event.payload;
|
|
47
|
+
this.auth = event.auth;
|
|
48
|
+
|
|
49
|
+
this.configFTP.host = utils.getValueOrNullControl(this.auth, "ftp.host", false, "ftp.islgrupo.com");
|
|
50
|
+
this.configFTP.user = utils.getValueOrNullControl(this.auth, "ftp.user", false, "");
|
|
51
|
+
this.configFTP.password = utils.getValueOrNullControl(this.auth, "ftp.password", false, "");
|
|
52
|
+
this.ftpFolders.podFolder = utils.getValueOrNullControl(this.auth, "ftp.podFolder", false, "");
|
|
53
|
+
|
|
54
|
+
if (utils.getValueOrNull(this.auth, "ftp.port")) this.configFTP.port = this.auth.ftp.port;
|
|
55
|
+
|
|
56
|
+
this.DEBUG = DEBUG;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
s3 = {
|
|
60
|
+
upload: async (data, path) => {
|
|
61
|
+
return await s3bucket.uploadToS3(path, data, {
|
|
62
|
+
ContentEncoding: "base64", ContentType: "image/png",
|
|
63
|
+
});
|
|
64
|
+
}, download: async (path) => {
|
|
65
|
+
return await s3bucket.downloadFileFromS3(path);
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
http = {
|
|
69
|
+
get: async (URL, params, headers = {}) => {
|
|
70
|
+
return await axiosRequest.get(URL, {
|
|
71
|
+
auth: {}, logId: this.logGroupName, headers: {...headers}, ...params
|
|
72
|
+
});
|
|
73
|
+
}, delete: async (URL, params, headers) => {
|
|
74
|
+
return await axiosRequest.deletion(URL, {
|
|
75
|
+
auth: {}, logId: this.logGroupName, headers: {...headers}, ...params
|
|
76
|
+
});
|
|
77
|
+
}, post: async (URL, params, headers) => {
|
|
78
|
+
return await axiosRequest.post(URL, {
|
|
79
|
+
auth: {}, logId: this.logGroupName, headers: {...headers}, ...params,
|
|
80
|
+
});
|
|
81
|
+
}, put: async (URL, params, headers) => {
|
|
82
|
+
return await axiosRequest.put(URL, {
|
|
83
|
+
auth: {}, logId: this.logGroupName, headers: {...headers}, ...params
|
|
84
|
+
});
|
|
85
|
+
}, downloadFile: async (method, URL, params, s3Path) => {
|
|
86
|
+
let response = await axiosRequest[method](URL, {
|
|
87
|
+
auth: {}, logId: this.logGroupName, headers: {}, config: {responseType: 'arraybuffer'}, ...params
|
|
88
|
+
});
|
|
89
|
+
let buff = Buffer.from(response.data, "binary");
|
|
90
|
+
let s3PathUploaded = await this.s3.upload(buff, s3Path);
|
|
91
|
+
return s3PathUploaded;
|
|
92
|
+
}, postForm: async (URL, {attachment, document}, _headers) => {
|
|
93
|
+
const formData = new FormData();
|
|
94
|
+
formData.append('document', JSON.stringify(document));
|
|
95
|
+
formData.append('attachment', attachment, "document.pdf");
|
|
96
|
+
|
|
97
|
+
const config = {
|
|
98
|
+
method: 'post', url: URL, headers: {
|
|
99
|
+
'Authorization': _headers.Authorization, ...formData.getHeaders(),
|
|
100
|
+
}, data: formData
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
return await axios.request(config);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
ftp = {
|
|
112
|
+
connect: async () => {
|
|
113
|
+
try {
|
|
114
|
+
//Connect to FTP
|
|
115
|
+
this.ftpConnection = new promiseFTP();
|
|
116
|
+
await this.ftpConnection.connect(this.configFTP);
|
|
117
|
+
this.logMessage(`Correctly Connected To FTP`, true);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw {message: "Error from FTP"};
|
|
120
|
+
}
|
|
121
|
+
}, listFolder: async (folderAndRegexp) => {
|
|
122
|
+
if (!this.ftpConnection) throw {message: "No connection was stablished"};
|
|
123
|
+
let files = await this.ftpConnection.list(folderAndRegexp);
|
|
124
|
+
if (!files || files.length < 1) throw {message: "No files were found"};
|
|
125
|
+
this.logMessage(`Files Found: ${files.map((f) => f.name)}`);
|
|
126
|
+
return files;
|
|
127
|
+
}, download: async ({folder, file}) => {
|
|
128
|
+
if (!this.ftpConnection) throw {message: "No connection was stablished"};
|
|
129
|
+
let downloadedFile = await promiseFTPWrapper.downloadFromFTP(this.ftpConnection, `${folder}${file}`);
|
|
130
|
+
return downloadedFile;
|
|
131
|
+
}, putFile: async ({path, file}) => {
|
|
132
|
+
await promiseFTPWrapper.uploadFileToFTP(this.configFTP, file, path);
|
|
133
|
+
}, downloadFiles: async ({folder, _files, removeFiles = false}) => {
|
|
134
|
+
const files = [..._files];
|
|
135
|
+
if (!this.ftpConnection) throw {message: "No connection was stablished"};
|
|
136
|
+
for (let i = 0; i < files.length; i++) {
|
|
137
|
+
let file = await this.ftp.download({folder, file: files[i].name});
|
|
138
|
+
if (file) {
|
|
139
|
+
files[i].file = file;
|
|
140
|
+
if (removeFiles) await this.ftp.deleteFile(folder, files[i]);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return files;
|
|
144
|
+
}, deleteFile: async (folder, file) => {
|
|
145
|
+
await promiseFTPWrapper.deleteFileFromFTP(this.ftpConnection, `${folder}/${file}`);
|
|
146
|
+
}, closeConnection: async () => {
|
|
147
|
+
if (!this.ftpConnection) throw {message: "No connection was stablished"};
|
|
148
|
+
this.ftpConnection.end();
|
|
149
|
+
}, sortFiles: (filesList) => {
|
|
150
|
+
return filesList.sort((a, b) => {
|
|
151
|
+
const dateA = a.date;
|
|
152
|
+
const dateB = b.date;
|
|
153
|
+
if (dateA < dateB) {
|
|
154
|
+
return -1;
|
|
155
|
+
}
|
|
156
|
+
if (dateA > dateB) {
|
|
157
|
+
return 1;
|
|
158
|
+
}
|
|
159
|
+
return 0;
|
|
160
|
+
});
|
|
161
|
+
}, getJobMatchingFile: (file) => {
|
|
162
|
+
if (!file) throw {message: "No file was sent"};
|
|
163
|
+
let jobFound = [...this.jobs].find((job) => {
|
|
164
|
+
return String(file.name).includes(utils.getValueOrNull(job, "externalCarrier.trackingId"));
|
|
165
|
+
});
|
|
166
|
+
return jobFound;
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
logMessage = async (message) => {
|
|
171
|
+
await cloudwatch.putLogEvents(`${this.logUuid} ${message}`, this.logGroupName, 2, this.logStreamName);
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
logError = async (error) => {
|
|
175
|
+
await this.logMessage("(Error) : " + error.message ? error.message : JSON.stringify(error));
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
logStartingProcess = async () => {
|
|
179
|
+
await this.logMessage("Starting Process: Data received >>>" + utils.dataToString(this.event, "data").res, true);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
logSendingToCarrier = async (payload) => {
|
|
183
|
+
await this.logMessage(`Sending to ${this.carrier} ${utils.dataToString({...payload}, "data").res}`, true);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
logReceivedFromCarrier = async (payload, status) => {
|
|
187
|
+
await this.logMessage(`Received from ${this.carrier} (${status}) ${utils.dataToString({...payload}, "data").res}`, true);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
addSuccessResult = (payload) => {
|
|
191
|
+
this.results.totalSuccess++;
|
|
192
|
+
this.results.success.push(payload);
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
addErrorResult = (payload) => {
|
|
196
|
+
this.results.totalError++;
|
|
197
|
+
this.results.error.push(payload);
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
clearResults = () => {
|
|
201
|
+
this.results = {
|
|
202
|
+
totalError: 0, totalSuccess: 0, error: [], success: [],
|
|
203
|
+
};
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
bulkAddSuccessResult = (extra = {}) => {
|
|
207
|
+
this.clearResults();
|
|
208
|
+
this.jobs.forEach((job) => this.addSuccessResult({
|
|
209
|
+
_id: job._id, trackingId: job.externalCarrier.trackingId, ...extra,
|
|
210
|
+
}));
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
bulkAddErrorResult = (error) => {
|
|
214
|
+
this.clearResults();
|
|
215
|
+
this.jobs.forEach((job) => this.addErrorResult({
|
|
216
|
+
_id: job._id,
|
|
217
|
+
trackingId: job.externalCarrier.trackingId,
|
|
218
|
+
code: error.code || 417,
|
|
219
|
+
message: error.message || "Something Went Wrong",
|
|
220
|
+
carrierCode: error.carrierCode || "tookaneCode",
|
|
221
|
+
carrierMessage: error.carrierMessage || "Something Went Wrong",
|
|
222
|
+
}));
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
logFinishProcess = async ({error} = {}) => {
|
|
226
|
+
if (this.results.totalError || error) {
|
|
227
|
+
error = error && error.message ? error.message : error;
|
|
228
|
+
await this.logMessage("Finsish Process with errors: " + (error || "") + " " + JSON.stringify(this.results));
|
|
229
|
+
} else {
|
|
230
|
+
await this.logMessage("Finsish Process Sucessfully: " + JSON.stringify(this.results));
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
validatePayload = () => {
|
|
235
|
+
if (this.jobs.length < 1) throw {message: "No Jobs were sent"};
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
getJobsByTrackingId = () => {
|
|
239
|
+
let objToReturn = {};
|
|
240
|
+
this.jobs.forEach((job) => {
|
|
241
|
+
let valueFound = utils.getValueOrNull(job, "externalCarrier.trackingId");
|
|
242
|
+
if (valueFound) objToReturn[job._id] = {trackingId: valueFound};
|
|
243
|
+
objToReturn[job._id].jobOwner = {
|
|
244
|
+
account: {_id: job.jobOwner.account._id},
|
|
245
|
+
};
|
|
246
|
+
});
|
|
247
|
+
return objToReturn;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
endSuccess = () => {
|
|
251
|
+
return {
|
|
252
|
+
isBase64Encoded: false, statusCode: 200, body: utils.dataToString(this.results, "data").res,
|
|
253
|
+
};
|
|
254
|
+
};
|
|
255
|
+
endError = (e) => {
|
|
256
|
+
let {code, res} = utils.dataToString(e);
|
|
257
|
+
let body = {
|
|
258
|
+
code, message: res, carrierCode: e.carrierCode, carrierMessage: e.carrierMessage,
|
|
259
|
+
};
|
|
260
|
+
return {isBase64Encoded: false, statusCode: code ? code : 417, body: res};
|
|
261
|
+
};
|
|
262
|
+
getToken = () => {
|
|
263
|
+
const token = `${this.auth.username}:${this.auth.password}`;
|
|
264
|
+
const encodedToken = Buffer.from(token).toString("base64");
|
|
265
|
+
return encodedToken;
|
|
266
|
+
};
|
|
267
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#### models
|
|
2
|
+
each file represents the collections/models name in the mongo database.
|
|
3
|
+
|
|
4
|
+
#### index.js
|
|
5
|
+
extend the export by including the models/{collections}
|
|
6
|
+
|
|
7
|
+
### Example usage from Lambda JS:
|
|
8
|
+
```
|
|
9
|
+
const db = await pelMongo.connectToDatabase({
|
|
10
|
+
MONGODB_URI: 'Connection String',
|
|
11
|
+
MONGODB_DATABASE: 'Database Name'
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
let users = pelMongo.findAllUsers(db);
|
|
15
|
+
console.log(users);
|
|
16
|
+
```
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Import dependency.
|
|
3
|
+
const {MongoClient} = require('mongodb');
|
|
4
|
+
|
|
5
|
+
// Function for connecting to MongoDB, returning a new or cached database connection
|
|
6
|
+
module.exports.connectToDatabase = async function connectToDatabase(params) {
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
// Connection string to the database
|
|
10
|
+
const uri = params.MONGODB_URI;
|
|
11
|
+
const database = params.MONGODB_DATABASE;
|
|
12
|
+
|
|
13
|
+
// Cached connection promise
|
|
14
|
+
let cachedPromise = null;
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
if (!cachedPromise) {
|
|
18
|
+
// If no connection promise is cached, create a new one. We cache the promise instead
|
|
19
|
+
// of the connection itself to prevent race conditions where connect is called more than
|
|
20
|
+
// once. The promise will resolve only once.
|
|
21
|
+
// Node.js driver docs can be found at http://mongodb.github.io/node-mongodb-native/.
|
|
22
|
+
cachedPromise =
|
|
23
|
+
MongoClient.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true});
|
|
24
|
+
}
|
|
25
|
+
// await on the promise. This resolves only once.
|
|
26
|
+
const client = await cachedPromise;
|
|
27
|
+
|
|
28
|
+
// Specify which database we want to use
|
|
29
|
+
const db = await client.db(database);
|
|
30
|
+
|
|
31
|
+
return db;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* This function is similar to the above function `connectToDatabase`.
|
|
36
|
+
* The difference is that we don't need to pass the database name in the params.
|
|
37
|
+
* It works just with the connection string.
|
|
38
|
+
* @param MONGODB_URI
|
|
39
|
+
* @returns {Promise<null>}
|
|
40
|
+
*/
|
|
41
|
+
module.exports.connectToDatabaseWithURI = async function connectToDatabase(MONGODB_URI) {
|
|
42
|
+
|
|
43
|
+
// Cached connection promise
|
|
44
|
+
let cachedPromise = null;
|
|
45
|
+
|
|
46
|
+
if (!cachedPromise) {
|
|
47
|
+
// If no connection promise is cached, create a new one. We cache the promise instead
|
|
48
|
+
// of the connection itself to prevent race conditions where connect is called more than
|
|
49
|
+
// once. The promise will resolve only once.
|
|
50
|
+
// Node.js driver docs can be found at http://mongodb.github.io/node-mongodb-native/.
|
|
51
|
+
cachedPromise = MongoClient.connect(MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true});
|
|
52
|
+
}
|
|
53
|
+
// await on the promise. This resolves only once.
|
|
54
|
+
const client = await cachedPromise;
|
|
55
|
+
// Specify which database we want to use
|
|
56
|
+
return client;
|
|
57
|
+
};
|
package/mongodb/index.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
let GLOBAL_MONGO_LIMIT = 10;
|
|
2
|
+
let GLOBAL_MONGO_OFFSET = 0;
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* to find all the users in the DB
|
|
6
|
+
* @param db
|
|
7
|
+
* @param limit
|
|
8
|
+
* @param offset
|
|
9
|
+
* @returns {Promise<void>}
|
|
10
|
+
*/
|
|
11
|
+
const findAllUsers = async (db, limit = GLOBAL_MONGO_LIMIT, offset = GLOBAL_MONGO_OFFSET) => {
|
|
12
|
+
db.collection('users').find({}).limit(limit).skip(offset).toArray(function (err, result) {
|
|
13
|
+
if (err) {
|
|
14
|
+
console.log(err);
|
|
15
|
+
} else {
|
|
16
|
+
console.log(result);
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* to find user by ID
|
|
24
|
+
* @param db
|
|
25
|
+
* @param userId
|
|
26
|
+
* @returns {Promise<void>}
|
|
27
|
+
*/
|
|
28
|
+
const findByUserID = async (db, userId) => {
|
|
29
|
+
db.collection('users').findOne({
|
|
30
|
+
_id: new mongo.ObjectID(userId)
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* to find user by email
|
|
36
|
+
* @param db
|
|
37
|
+
* @param email
|
|
38
|
+
* @returns {Promise<void>}
|
|
39
|
+
*/
|
|
40
|
+
const findByEmail = async (db, email) => {
|
|
41
|
+
db.collection('users').findOne({
|
|
42
|
+
email: email
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
//export the methods
|
|
47
|
+
module.exports = {
|
|
48
|
+
findAllUsers,
|
|
49
|
+
findByUserID,
|
|
50
|
+
findByEmail
|
|
51
|
+
}
|