@itentialopensource/adapter-microsoft_graph 1.4.7 → 1.5.0
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/.eslintrc.js +1 -0
- package/AUTH.md +4 -4
- package/BROKER.md +4 -4
- package/CALLS.md +9 -9
- package/ENHANCE.md +3 -3
- package/PROPERTIES.md +24 -9
- package/README.md +24 -23
- package/SUMMARY.md +2 -2
- package/SYSTEMINFO.md +1 -1
- package/TAB1.md +2 -2
- package/TAB2.md +17 -11
- package/TROUBLESHOOT.md +10 -1
- package/UTILITIES.md +473 -0
- package/adapter.js +5 -5
- package/adapterBase.js +52 -16
- package/package.json +24 -28
- package/pronghorn.json +15 -13
- package/propertiesSchema.json +68 -7
- package/report/adapterInfo.json +7 -7
- package/report/auto-adapter-openapi.json +8063 -0
- package/report/updateReport1748551976792.json +120 -0
- package/sampleProperties.json +4 -0
- package/test/integration/adapterTestBasicGet.js +88 -54
- package/test/integration/adapterTestConnectivity.js +15 -16
- package/test/integration/adapterTestIntegration.js +1 -38
- package/test/unit/adapterBaseTestUnit.js +641 -39
- package/test/unit/adapterTestUnit.js +17 -54
- package/utils/adapterInfo.js +114 -164
- package/utils/argParser.js +44 -0
- package/utils/checkMigrate.js +77 -38
- package/utils/entitiesToDB.js +53 -42
- package/utils/logger.js +26 -0
- package/utils/modify.js +56 -55
- package/utils/mongoDbConnection.js +79 -0
- package/utils/mongoUtils.js +162 -0
- package/utils/taskMover.js +31 -32
- package/utils/tbScript.js +36 -172
- package/utils/tbUtils.js +84 -226
- package/utils/troubleshootingAdapter.js +68 -84
- package/utils/updateAdapterConfig.js +158 -0
- package/utils/addAuth.js +0 -94
- package/utils/artifactize.js +0 -146
- package/utils/basicGet.js +0 -50
- package/utils/packModificationScript.js +0 -35
- package/utils/patches2bundledDeps.js +0 -90
package/utils/entitiesToDB.js
CHANGED
@@ -16,18 +16,19 @@
|
|
16
16
|
|
17
17
|
const fs = require('fs');
|
18
18
|
const path = require('path');
|
19
|
-
const
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
const
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
19
|
+
const tbUtils = require('./tbUtils');
|
20
|
+
const mongoUtils = require('./mongoUtils');
|
21
|
+
|
22
|
+
/**
|
23
|
+
* Function to load sample properties from the file system
|
24
|
+
*/
|
25
|
+
const loadSampleProperties = async () => {
|
26
|
+
const samplePath = path.join(__dirname, '../sampleProperties.json');
|
27
|
+
if (fs.existsSync(samplePath)) {
|
28
|
+
const fullProps = JSON.parse(fs.readFileSync(samplePath, 'utf-8'));
|
29
|
+
return fullProps.properties.mongo;
|
30
|
+
}
|
31
|
+
throw new Error('sampleProperties.json not found');
|
31
32
|
};
|
32
33
|
|
33
34
|
/**
|
@@ -77,22 +78,23 @@ const buildDoc = (pathstring) => {
|
|
77
78
|
/**
|
78
79
|
* Function used to get the database from the options or a provided directory
|
79
80
|
*/
|
80
|
-
const optionsHandler = (options) => {
|
81
|
-
|
82
|
-
|
83
|
-
|
84
|
-
|
85
|
-
|
86
|
-
|
87
|
-
|
88
|
-
|
89
|
-
|
90
|
-
|
91
|
-
|
81
|
+
const optionsHandler = async (options) => {
|
82
|
+
try {
|
83
|
+
// Try mongo properties from service config first
|
84
|
+
const mongoPronghornProps = options?.pronghornProps?.mongo;
|
85
|
+
const validatedPronghornProps = mongoPronghornProps ? mongoUtils.getAndValidateMongoProps(mongoPronghornProps) : undefined;
|
86
|
+
if (validatedPronghornProps) return validatedPronghornProps;
|
87
|
+
|
88
|
+
// Fallback to sample properties
|
89
|
+
const sampleProps = await loadSampleProperties();
|
90
|
+
const validatedSampleProps = mongoUtils.getAndValidateMongoProps(sampleProps);
|
91
|
+
if (validatedSampleProps) return validatedSampleProps;
|
92
|
+
|
93
|
+
throw new Error('No mongo properties provided! Need either a complete URL or both host and database');
|
94
|
+
} catch (error) {
|
95
|
+
log.error('Error in optionsHandler:', error.message);
|
96
|
+
throw error;
|
92
97
|
}
|
93
|
-
|
94
|
-
// if nothing was provided, error
|
95
|
-
return new Promise((resolve, reject) => reject(new Error('Neither pronghornProps nor iapDir defined in options!')));
|
96
98
|
};
|
97
99
|
|
98
100
|
/**
|
@@ -102,6 +104,7 @@ const moveEntitiesToDB = async (targetPath, options) => {
|
|
102
104
|
// set local variables
|
103
105
|
let myOpts = options;
|
104
106
|
let myPath = targetPath;
|
107
|
+
let mongoConnection = null;
|
105
108
|
|
106
109
|
// if we got a string parse into a JSON object
|
107
110
|
if (typeof myOpts === 'string') {
|
@@ -118,15 +121,17 @@ const moveEntitiesToDB = async (targetPath, options) => {
|
|
118
121
|
throw new Error('Adapter ID required!');
|
119
122
|
}
|
120
123
|
|
121
|
-
//
|
122
|
-
|
123
|
-
//
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
124
|
+
// Check valid filepath provided
|
125
|
+
if (!myPath) {
|
126
|
+
// if no path use the current directory without the utils
|
127
|
+
myPath = path.join(__dirname, '../');
|
128
|
+
} else if (myPath.slice(-1) === '/') {
|
129
|
+
myPath = myPath.slice(0, -1);
|
130
|
+
}
|
131
|
+
|
132
|
+
try {
|
133
|
+
// get the database properties from adapter service instance configs
|
134
|
+
const currentProps = await optionsHandler(options);
|
130
135
|
|
131
136
|
// verify set the entity path
|
132
137
|
const entitiesPath = `${myPath}/entities`;
|
@@ -165,15 +170,21 @@ const moveEntitiesToDB = async (targetPath, options) => {
|
|
165
170
|
});
|
166
171
|
|
167
172
|
// Upload documents to db collection
|
168
|
-
|
169
|
-
if (!
|
170
|
-
|
173
|
+
mongoConnection = await tbUtils.connect(currentProps).catch((err) => { log.error(err); throw err; });
|
174
|
+
if (!mongoConnection) {
|
175
|
+
log.error('Error occurred when connecting to database', currentProps);
|
171
176
|
throw new Error('Database not found');
|
172
177
|
}
|
173
|
-
|
174
|
-
const
|
178
|
+
|
179
|
+
const collection = mongoConnection.db.collection(myOpts.targetCollection);
|
180
|
+
const res = await collection.insertMany(docs, { checkKeys: false }).catch((err) => { log.error(err); throw err; });
|
175
181
|
return res;
|
176
|
-
}
|
182
|
+
} finally {
|
183
|
+
// Ensure connection is closed even if an error occurs
|
184
|
+
if (mongoConnection) {
|
185
|
+
await tbUtils.closeConnection(mongoConnection);
|
186
|
+
}
|
187
|
+
}
|
177
188
|
};
|
178
189
|
|
179
190
|
module.exports = { moveEntitiesToDB };
|
package/utils/logger.js
ADDED
@@ -0,0 +1,26 @@
|
|
1
|
+
// utils/logger.js
|
2
|
+
const winston = require('winston');
|
3
|
+
const { parseArgs } = require('./argParser');
|
4
|
+
|
5
|
+
const customLevels = {
|
6
|
+
spam: 6,
|
7
|
+
trace: 5,
|
8
|
+
debug: 4,
|
9
|
+
info: 3,
|
10
|
+
warn: 2,
|
11
|
+
error: 1,
|
12
|
+
none: 0
|
13
|
+
};
|
14
|
+
|
15
|
+
// Only set global logger if it doesn't already exist (i.e., not provided by app)
|
16
|
+
if (!global.log) {
|
17
|
+
const { logLevel = 'info' } = parseArgs();
|
18
|
+
|
19
|
+
global.log = winston.createLogger({
|
20
|
+
level: logLevel,
|
21
|
+
levels: customLevels,
|
22
|
+
transports: [new winston.transports.Console()]
|
23
|
+
});
|
24
|
+
}
|
25
|
+
|
26
|
+
module.exports = global.log;
|
package/utils/modify.js
CHANGED
@@ -1,29 +1,7 @@
|
|
1
1
|
const { execSync } = require('child_process');
|
2
2
|
const fs = require('fs-extra');
|
3
|
-
const Ajv = require('ajv');
|
4
3
|
const rls = require('readline-sync');
|
5
4
|
const { existsSync } = require('fs-extra');
|
6
|
-
const { getAdapterConfig } = require('./tbUtils');
|
7
|
-
const { name } = require('../package.json');
|
8
|
-
const propertiesSchema = require('../propertiesSchema.json');
|
9
|
-
|
10
|
-
const flags = process.argv[2];
|
11
|
-
|
12
|
-
/**
|
13
|
-
* @summary Updates database instance with new adapter properties
|
14
|
-
*
|
15
|
-
* @function updateServiceItem
|
16
|
-
*/
|
17
|
-
async function updateServiceItem() {
|
18
|
-
const { database, serviceItem } = await getAdapterConfig();
|
19
|
-
const currentProps = serviceItem.properties.properties;
|
20
|
-
const ajv = new Ajv({ allErrors: true, useDefaults: true });
|
21
|
-
const validate = ajv.compile(propertiesSchema);
|
22
|
-
validate(currentProps);
|
23
|
-
console.log('Updating Properties...');
|
24
|
-
await database.collection('service_configs').updateOne({ model: name }, { $set: serviceItem });
|
25
|
-
console.log('Properties Updated');
|
26
|
-
}
|
27
5
|
|
28
6
|
/**
|
29
7
|
* @summary Creates a backup zip file of current adapter
|
@@ -70,21 +48,20 @@ function revertMod() {
|
|
70
48
|
fs.removeSync(file);
|
71
49
|
}
|
72
50
|
});
|
73
|
-
//
|
51
|
+
// unzip previousVersion, reinstall dependencies and delete zipfile
|
74
52
|
execSync('unzip -o previousVersion.zip && rm -rf node_modules && rm package-lock.json && npm install', { maxBuffer: 1024 * 1024 * 2 });
|
75
53
|
execSync('rm previousVersion.zip');
|
76
54
|
console.log('Changes have been reverted');
|
77
55
|
}
|
78
56
|
|
79
|
-
|
80
|
-
|
81
|
-
|
82
|
-
|
83
|
-
if (!
|
84
|
-
|
85
|
-
process.exit();
|
57
|
+
/**
|
58
|
+
* @summary Handle migration logic
|
59
|
+
*/
|
60
|
+
function handleMigration() {
|
61
|
+
if (!existsSync('migrationPackage.zip')) {
|
62
|
+
throw new Error('Migration Package not found. Download and place migrationPackage in the adapter root directory');
|
86
63
|
}
|
87
|
-
|
64
|
+
|
88
65
|
backup();
|
89
66
|
console.log('Migrating adapter and running tests...');
|
90
67
|
const migrateCmd = 'unzip -o migrationPackage.zip'
|
@@ -92,61 +69,85 @@ if (flags === '-m') {
|
|
92
69
|
+ ' && node migrate';
|
93
70
|
const migrateOutput = execSync(migrateCmd, { encoding: 'utf-8' });
|
94
71
|
console.log(migrateOutput);
|
95
|
-
|
96
|
-
|
72
|
+
|
73
|
+
if (migrateOutput.includes('Lint exited with code 1') || migrateOutput.includes('Tests exited with code 1')) {
|
97
74
|
if (rls.keyInYN('Adapter failed tests or lint after migrating. Would you like to revert the changes?')) {
|
98
75
|
console.log('Reverting changes...');
|
99
76
|
revertMod();
|
100
|
-
|
77
|
+
throw new Error('Adapter failed tests or lint after migrating. Changes reverted');
|
101
78
|
}
|
102
79
|
console.log('Adapter Migration will continue. If you want to revert the changes, run the command npm run adapter:revert');
|
103
80
|
}
|
81
|
+
|
104
82
|
console.log('Installing new dependencies..');
|
105
83
|
const updatePackageCmd = 'rm -rf node_modules && rm package-lock.json && npm install';
|
106
84
|
const updatePackageOutput = execSync(updatePackageCmd, { encoding: 'utf-8' });
|
107
85
|
console.log(updatePackageOutput);
|
108
86
|
console.log('New dependencies installed');
|
109
|
-
|
110
|
-
updateServiceItem().then(() => {
|
111
|
-
console.log('Adapter Successfully Migrated. Restart adapter in IAP to apply the changes');
|
112
|
-
archiveMod('MIG');
|
113
|
-
process.exit();
|
114
|
-
});
|
87
|
+
archiveMod('MIG');
|
115
88
|
}
|
116
89
|
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
121
|
-
|
90
|
+
/**
|
91
|
+
* @summary Handle update logic
|
92
|
+
*/
|
93
|
+
function handleUpdate() {
|
94
|
+
if (!existsSync('updatePackage.zip')) {
|
95
|
+
throw new Error('Update Package not found. Download and place updateAdapter.zip in the adapter root directory');
|
122
96
|
}
|
123
|
-
|
97
|
+
|
124
98
|
backup();
|
125
99
|
const updateCmd = 'unzip -o updatePackage.zip'
|
126
100
|
+ ' && cd adapter_modifications'
|
127
101
|
+ ' && node update.js updateFiles';
|
128
102
|
execSync(updateCmd, { encoding: 'utf-8' });
|
129
103
|
const updateOutput = execSync(updateCmd, { encoding: 'utf-8' });
|
130
|
-
|
131
|
-
|
104
|
+
|
105
|
+
if (updateOutput.includes('Lint exited with code 1') || updateOutput.includes('Tests exited with code 1')) {
|
132
106
|
if (rls.keyInYN('Adapter failed tests or lint after updating. Would you like to revert the changes?')) {
|
133
107
|
console.log('Reverting changes...');
|
134
108
|
revertMod();
|
135
|
-
|
109
|
+
throw new Error('Adapter failed tests or lint after updating. Changes reverted');
|
136
110
|
}
|
137
111
|
console.log('Adapter Update will continue. If you want to revert the changes, run the command npm run adapter:revert');
|
138
112
|
}
|
113
|
+
|
139
114
|
console.log(updateOutput);
|
140
115
|
console.log('Adapter Successfully Updated. Restart adapter in IAP to apply the changes');
|
141
116
|
archiveMod('UPD');
|
142
|
-
process.exit();
|
143
117
|
}
|
144
118
|
|
145
|
-
|
146
|
-
|
147
|
-
|
148
|
-
|
149
|
-
|
119
|
+
/**
|
120
|
+
* @summary Handle revert logic
|
121
|
+
*/
|
122
|
+
function handleRevert() {
|
123
|
+
if (!existsSync('previousVersion.zip')) {
|
124
|
+
throw new Error('Previous adapter version not found. There are no changes to revert');
|
150
125
|
}
|
151
126
|
revertMod();
|
152
127
|
}
|
128
|
+
|
129
|
+
/**
|
130
|
+
* @summary Entrypoint for the script
|
131
|
+
*/
|
132
|
+
function main() {
|
133
|
+
const flags = process.argv[2];
|
134
|
+
|
135
|
+
switch (flags) {
|
136
|
+
case '-m':
|
137
|
+
return handleMigration();
|
138
|
+
case '-u':
|
139
|
+
return handleUpdate();
|
140
|
+
case '-r':
|
141
|
+
return handleRevert();
|
142
|
+
default:
|
143
|
+
throw new Error('Invalid flag. Use -m for migrate, -u for update, or -r for revert.');
|
144
|
+
}
|
145
|
+
}
|
146
|
+
|
147
|
+
try {
|
148
|
+
main();
|
149
|
+
process.exit(0);
|
150
|
+
} catch (error) {
|
151
|
+
console.error(error.message || error);
|
152
|
+
process.exit(1);
|
153
|
+
}
|
@@ -0,0 +1,79 @@
|
|
1
|
+
// Set globals
|
2
|
+
/* global log */
|
3
|
+
|
4
|
+
const { MongoClient } = require('mongodb');
|
5
|
+
const MongoUtils = require('./mongoUtils');
|
6
|
+
|
7
|
+
class MongoDBConnection {
|
8
|
+
constructor(properties) {
|
9
|
+
this.properties = properties;
|
10
|
+
this.initialize(properties);
|
11
|
+
}
|
12
|
+
|
13
|
+
initialize(properties) {
|
14
|
+
const {
|
15
|
+
url, database, maxPoolSize, appname
|
16
|
+
} = properties;
|
17
|
+
|
18
|
+
// Handle URL first - if provided, it takes precedence
|
19
|
+
if (url) {
|
20
|
+
const urlObj = new URL(url);
|
21
|
+
const urlDbName = urlObj.pathname.slice(1);
|
22
|
+
this.dbName = database || urlDbName;
|
23
|
+
|
24
|
+
// Update URL if database name is different
|
25
|
+
if (this.dbName !== urlDbName) {
|
26
|
+
urlObj.pathname = `${this.dbName}`;
|
27
|
+
}
|
28
|
+
|
29
|
+
this.url = urlObj.toString();
|
30
|
+
} else {
|
31
|
+
const connectionObj = MongoUtils.generateConnectionObj(properties);
|
32
|
+
this.url = MongoUtils.generateConnectionString(connectionObj);
|
33
|
+
this.dbName = database;
|
34
|
+
}
|
35
|
+
|
36
|
+
// Set options using generateTlsSettings
|
37
|
+
this.options = MongoUtils.generateTlsSettings(properties);
|
38
|
+
|
39
|
+
// Add maxPoolSize if configured
|
40
|
+
if (maxPoolSize > 0 && maxPoolSize <= 65535) {
|
41
|
+
this.options.maxPoolSize = maxPoolSize;
|
42
|
+
}
|
43
|
+
|
44
|
+
// Add application name if provided
|
45
|
+
if (appname) {
|
46
|
+
this.options.appname = appname;
|
47
|
+
}
|
48
|
+
}
|
49
|
+
|
50
|
+
async closeConnection() {
|
51
|
+
if (this.connection && this.connection.close) {
|
52
|
+
try {
|
53
|
+
await this.connection.close();
|
54
|
+
} catch (err) {
|
55
|
+
log.error(`Failed to close MongoDB connection - ${err.message}`);
|
56
|
+
}
|
57
|
+
}
|
58
|
+
}
|
59
|
+
|
60
|
+
async connect() {
|
61
|
+
const client = new MongoClient(this.url, this.options);
|
62
|
+
|
63
|
+
client.on('serverHeartbeatSucceeded', (msg) => log.info(`Connection established and heartbeat succeeded - ${JSON.stringify(msg)}`));
|
64
|
+
client.on('connectionClosed', (msg) => log.info(`Connection closed - ${JSON.stringify(msg)}`));
|
65
|
+
client.on('error', (msg) => log.error(`Connection error - ${JSON.stringify(msg)}`));
|
66
|
+
client.on('commandFailed', (msg) => log.error(`Command failed - ${JSON.stringify(msg)}`));
|
67
|
+
client.on('serverHeartbeatFailed', (msg) => log.error(`Connection timeout - ${JSON.stringify(msg)}`));
|
68
|
+
|
69
|
+
await client.connect().catch((error) => {
|
70
|
+
throw new Error(MongoUtils.resolveMongoError(error));
|
71
|
+
});
|
72
|
+
|
73
|
+
this.db = client.db(this.dbName);
|
74
|
+
this.connection = client;
|
75
|
+
return this;
|
76
|
+
}
|
77
|
+
}
|
78
|
+
|
79
|
+
module.exports = MongoDBConnection;
|
@@ -0,0 +1,162 @@
|
|
1
|
+
const fs = require('fs-extra');
|
2
|
+
|
3
|
+
class MongoUtils {
|
4
|
+
/**
|
5
|
+
* Parses a MongoDB connection string and extracts its components.
|
6
|
+
* @param {string} connectionString - The MongoDB connection string.
|
7
|
+
* @returns {object} Parsed connection details.
|
8
|
+
*/
|
9
|
+
static parseConnectionString(connectionString) {
|
10
|
+
try {
|
11
|
+
const url = new URL(connectionString);
|
12
|
+
return {
|
13
|
+
protocol: url.protocol.replace(':', ''),
|
14
|
+
host: url.hostname,
|
15
|
+
port: url.port || '27017',
|
16
|
+
database: url.pathname.replace('/', ''),
|
17
|
+
username: url.username || null,
|
18
|
+
password: url.password || null,
|
19
|
+
options: Object.fromEntries(url.searchParams.entries())
|
20
|
+
};
|
21
|
+
} catch (error) {
|
22
|
+
throw new Error(`Invalid MongoDB URI: ${error.message}`);
|
23
|
+
}
|
24
|
+
}
|
25
|
+
|
26
|
+
/**
|
27
|
+
* Generates a MongoDB connection string from given properties.
|
28
|
+
* @param {object} config - MongoDB connection properties.
|
29
|
+
* @returns {string} A valid MongoDB connection string.
|
30
|
+
*/
|
31
|
+
static generateConnectionString(config) {
|
32
|
+
// Determine protocol based on addSrv flag
|
33
|
+
const protocol = config.addSrv ? 'mongodb+srv' : 'mongodb';
|
34
|
+
|
35
|
+
// Build authentication part if credentials are provided and dbAuth is true
|
36
|
+
const authPart = (config.dbAuth && config.username && config.password)
|
37
|
+
? `${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@`
|
38
|
+
: '';
|
39
|
+
|
40
|
+
// Build host and port part
|
41
|
+
const hostPart = config.host;
|
42
|
+
const portPart = !config.addSrv && config.port ? `:${config.port}` : '';
|
43
|
+
|
44
|
+
// Build options part
|
45
|
+
let optionsPart = '';
|
46
|
+
if (config.options && Object.keys(config.options).length) {
|
47
|
+
optionsPart = `?${new URLSearchParams(config.options).toString()}`;
|
48
|
+
}
|
49
|
+
|
50
|
+
// Build database part
|
51
|
+
const dbPart = config.database ? `/${config.database}` : '';
|
52
|
+
|
53
|
+
return `${protocol}://${authPart}${hostPart}${portPart}${dbPart}${optionsPart}`;
|
54
|
+
}
|
55
|
+
|
56
|
+
/**
|
57
|
+
* Generates TLS settings for MongoDB connection
|
58
|
+
* @param {object} properties - Connection properties containing TLS configuration
|
59
|
+
* @returns {object} TLS settings object
|
60
|
+
*/
|
61
|
+
static generateTlsSettings(properties) {
|
62
|
+
// Handle TLS properties
|
63
|
+
if (properties.tls) {
|
64
|
+
return {
|
65
|
+
tls: properties.tls.enabled,
|
66
|
+
tlsAllowInvalidCertificates: properties.tls.tlsAllowInvalidCertificates || false,
|
67
|
+
tlsCAFile: properties.tls.tlsCAFile
|
68
|
+
};
|
69
|
+
}
|
70
|
+
|
71
|
+
// Handle db_ssl properties (standard adapter format)
|
72
|
+
if (!properties.db_ssl) {
|
73
|
+
return { tls: false };
|
74
|
+
}
|
75
|
+
|
76
|
+
const tlsProperties = {
|
77
|
+
tls: properties.db_ssl.enabled || false,
|
78
|
+
tlsAllowInvalidCertificates: properties.db_ssl.accept_invalid_cert || false
|
79
|
+
};
|
80
|
+
|
81
|
+
const hasValidCaFile = properties.db_ssl.enabled && properties.db_ssl.ca_file && fs.existsSync(properties.db_ssl.ca_file);
|
82
|
+
|
83
|
+
if (hasValidCaFile) {
|
84
|
+
tlsProperties.tlsCAFile = properties.db_ssl.ca_file;
|
85
|
+
}
|
86
|
+
|
87
|
+
return tlsProperties;
|
88
|
+
}
|
89
|
+
|
90
|
+
/**
|
91
|
+
* Generates a connection object from properties
|
92
|
+
* @param {object} properties - Connection properties
|
93
|
+
* @returns {object} Connection object with host, port, database, and credentials
|
94
|
+
*/
|
95
|
+
static generateConnectionObj(properties) {
|
96
|
+
try {
|
97
|
+
const connectionObj = {
|
98
|
+
host: properties.host,
|
99
|
+
port: properties.port,
|
100
|
+
database: properties.database,
|
101
|
+
addSrv: properties.addSrv || false,
|
102
|
+
dbAuth: properties.dbAuth || false,
|
103
|
+
options: properties.replSet && !properties.addSrv ? { replicaSet: properties.replSet } : undefined
|
104
|
+
};
|
105
|
+
|
106
|
+
// Only include credentials if dbAuth is true
|
107
|
+
if (properties.dbAuth) {
|
108
|
+
// Validate that both username and password are provided when dbAuth is true
|
109
|
+
if (!properties.username || !properties.password) {
|
110
|
+
throw new Error('Both username and password are required when dbAuth is enabled');
|
111
|
+
}
|
112
|
+
connectionObj.username = properties.username;
|
113
|
+
connectionObj.password = properties.password;
|
114
|
+
}
|
115
|
+
|
116
|
+
return connectionObj;
|
117
|
+
} catch (error) {
|
118
|
+
throw new Error(`Invalid MongoDB configuration: ${error.message}`);
|
119
|
+
}
|
120
|
+
}
|
121
|
+
|
122
|
+
/**
|
123
|
+
* Resolves MongoDB error messages to user-friendly format
|
124
|
+
* @param {object} mongoError - The MongoDB error object
|
125
|
+
* @returns {string} User-friendly error message
|
126
|
+
*/
|
127
|
+
static resolveMongoError(mongoError) {
|
128
|
+
if (mongoError && mongoError.code === 13) {
|
129
|
+
return 'User unauthorized to perform the requested action: ';
|
130
|
+
}
|
131
|
+
if (mongoError && mongoError.code === 18) {
|
132
|
+
return `User Authentication failed. Username/Password combination is incorrect ${mongoError}`;
|
133
|
+
}
|
134
|
+
return mongoError;
|
135
|
+
}
|
136
|
+
|
137
|
+
/**
|
138
|
+
* Helper function to validate and process MongoDB connection properties
|
139
|
+
* @param {Object} mongoProps - MongoDB connection properties to validate
|
140
|
+
* @returns {Object|undefined} - Validated and processed MongoDB properties or undefined if invalid
|
141
|
+
*/
|
142
|
+
static getAndValidateMongoProps(mongoProps) {
|
143
|
+
if (!mongoProps) return undefined;
|
144
|
+
|
145
|
+
// Handle URL-based connection
|
146
|
+
const url = mongoProps.url && mongoProps.url.trim();
|
147
|
+
if (!url) {
|
148
|
+
// Handle host-based connection
|
149
|
+
const hasHost = mongoProps.hostname || mongoProps.host;
|
150
|
+
const hasDatabase = mongoProps.database;
|
151
|
+
return (hasHost && hasDatabase) ? mongoProps : undefined;
|
152
|
+
}
|
153
|
+
|
154
|
+
// Process URL-based connection
|
155
|
+
const props = { ...mongoProps };
|
156
|
+
const { database } = props;
|
157
|
+
const urlHasDatabase = database && url.includes(`/${database}`);
|
158
|
+
return urlHasDatabase ? props : { ...props, url: `${url}/${database}` };
|
159
|
+
}
|
160
|
+
}
|
161
|
+
|
162
|
+
module.exports = MongoUtils;
|