Skip to content

Commit 1a5e127

Browse files
committed
fixed multiple mongodb databse connections! Services are now fetched for each app card, matching the user provied URL. Made changes to connect and servicesRequest channels in ipcMain.on in data.ts electron backend.
1 parent 9670831 commit 1a5e127

File tree

4 files changed

+170
-101
lines changed

4 files changed

+170
-101
lines changed

app/components/Occupied.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ const Occupied = React.memo(() => {
7878
// const [showAwsContainer, setShowAwsContainer] = useState(false);
7979
const navigate = useNavigate();
8080

81+
8182
// Grab services and applications whenever the user changes
8283
// v10: Runs once when Occupied is memoized, and subsequently when user is updated.
8384
useEffect(() => {
@@ -118,8 +119,9 @@ const Occupied = React.memo(() => {
118119
navigate(`/aws/:${app}`, { state: { typeOfService: selectedService } });
119120
} else {
120121
console.log('In handleClick Method (local) in Occupied.tsx');
121-
console.log('The following are the current values for appIndex, app, servicesData, and serviceModalOpen:');
122+
console.log('The following are the new values for appIndex, app, servicesData, and serviceModalOpen:');
122123
console.log(i, ' ', selectedApp, ' ', 'N/A ', serviceModalOpen );
124+
123125
setAppIndex(i);
124126
setApp(selectedApp);
125127
setServicesData([]);

app/modals/ServicesModal.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,16 @@ const ServicesModal: React.FC<ServicesModalProps> = React.memo(({ i, app }) => {
4141

4242
// v10: connectToDB function definition in Application Context.
4343
// parameters for connectToDB call: user, i (index), app (card title), app URL (url on card)
44-
// applications[i][2] refers to the local instance URI
44+
// applications[i][2] refers to the user provided URI
4545
useEffect(() => {
4646
console.log('Hi, inside useEffect in ServicesModal. Calling connectToDB function.');
4747
console.log("Passing the following parameters for user, i, app, applications, ");
4848
console.log(user, ' ', i, ' ', app, ' ', applications);
4949
connectToDB(user, i, app, applications[i][2]);
5050
}, [i]);
5151

52+
53+
5254
return (
5355
<div className="servicesContainer">
5456
{!servicesData.length ? (

electron/databases/mongo.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const testURL = 'mongodb+srv://seconddbtest:[email protected]
44
// Mongoose connection wrapped in function that takes the index of the selected database as the parameter. This index is used to target the correct database for querying.
55
const connectMongoose = async (i:number, URI: string) => {
66
try {
7-
await mongoose.connection.close();
7+
// await mongoose.connection.close();
88
const db = await mongoose.connect(URI);
99

1010
return db;

electron/routes/data.ts

Lines changed: 163 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -57,113 +57,167 @@ const settingsLocation = path.resolve(__dirname, '../../settings.json');
5757
* @desc Connects user to database and sets global currentDatabaseType which
5858
* is accessed in info.commsData and info.healthData
5959
*/
60-
ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, index: number, URI: string) => {
61-
try {
62-
// const isConnected = mongoose.connection.readyState === 1;
63-
// if (isConnected){
64-
// console.log('Connection to MongoDb has already been established.');
65-
// } else {
66-
67-
// }
68-
// Extract databaseType and URI from settings.json at particular index
69-
// get index from application context
7060

71-
// Connect to User database instantiated in 'dashboard.ts'
72-
if (username !== 'guest') {
73-
74-
const isConnected = mongoose.connection.readyState === 1;
61+
ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, index: number, URI: string) => {
62+
63+
try{
64+
const isConnected = mongoose.connection.readyState === 1;
7565
if (isConnected){
76-
console.log('Connection to MongoDb has already been established.');
77-
message.sender.send('databaseConnected', 'connection already established.');
78-
} else {
79-
return User.findOne({ username: username })
80-
.then(async (data) => {
81-
console.log('Hi, inside ipcMain.on connect in data.ts! Establishing connection to user provided database URI');
82-
const databaseType = data.services[index][1]
83-
const appURI = data.services[index][2]
84-
console.log('database type', databaseType);
85-
console.log('appURI', appURI);
86-
if (databaseType === 'MongoDB') {
87-
const shouldbedb = await connectMongo(index, appURI);
88-
// console.log(shouldbedb);
89-
// await connectMongo()
90-
currentDatabaseType = databaseType;
91-
message.sender.send('databaseConnected', 'connected!');
92-
} else if (databaseType === 'SQL') {
93-
pool = await connectPostgres(index, appURI);
94-
currentDatabaseType = databaseType;
66+
// console.log('Connection to MongoDb has already been established.');
67+
console.log('A connection to a mongoDB has already been establisehd.');
68+
mongoose.connection.close((error) => {
69+
if(error) {
70+
console.log('Error closing mongoDB connection: ', error);
71+
}
72+
else {
73+
console.log('MongoDB connection closed. Reconfiguring connection to new database.');
74+
mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true })
75+
.then(() => {
76+
console.log('Connected to user provided mongo database!');
77+
// testing database
78+
// ServicesModel.find()
79+
// .then(data => console.log(data))
80+
// .catch(err => console.log('error fetching services'));
81+
9582
message.sender.send('databaseConnected', 'connected!');
83+
})
84+
.catch(error => {
85+
console.log('Error connecting to MongoDB inside data.ts connection:', error);
86+
});
9687
}
97-
console.log('Established connection to user provided URL...');
98-
console.log('leaving ipcMain.on connect.')
99-
})
100-
.catch((error) => {
101-
console.log(` Error in connect, failed to load application : ${error}`)
102-
// return false;
103-
})
104-
}
88+
});
89+
} else {
90+
console.log('Database connection not found. Establishing connection...');
91+
// Connect to the proper database
92+
mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true })
93+
.then(() => {
94+
console.log('Connected to user provided mongo database!');
95+
// testing database
96+
// ServicesModel.find()
97+
// .then(data => console.log(data))
98+
// .catch(err => console.log('error fetching services'));
99+
100+
message.sender.send('databaseConnected', 'connected!');
101+
})
102+
.catch(error => {
103+
console.log('Error connecting to MongoDB inside data.ts connection:', error);
104+
});
105105

106-
// const MONGO_URI = URI
107-
// mongoose.connect(MONGO_URI, {
108-
// useNewUrlParser: true,
109-
// useUnifiedtopology: true,
110-
// })
111-
// test().catch((error) => console.log('error in second db', error));
112-
// async function test() {
113-
// const db2 = await mongoose.createConnection('mongodb+srv://seconddbtest:[email protected]/?retryWrites=true&w=majority');
114-
// console.log('connection to user provided db established..');
115-
// }
116-
// Check for existing user in DB, if found, connect to load application based on database type
117-
// return User.findOne({ username: username })
118-
// .then(async (data) => {
119-
// console.log('Hi, inside ipcMain.on connect in data.ts! Establishing connection to user provided database URI');
120-
// const databaseType = data.services[index][1]
121-
// const appURI = data.services[index][2]
122-
// console.log('database type', databaseType);
123-
// console.log('appURI', appURI);
124-
// if (databaseType === 'MongoDB') {
125-
// const shouldbedb = await connectMongo(index, appURI);
126-
// // console.log(shouldbedb);
127-
// // await connectMongo()
128-
// currentDatabaseType = databaseType;
129-
// message.sender.send('databaseConnected', 'connected!');
130-
// } else if (databaseType === 'SQL') {
131-
// pool = await connectPostgres(index, appURI);
132-
// currentDatabaseType = databaseType;
133-
// message.sender.send('databaseConnected', 'connected!');
134-
// }
135-
// console.log('Established connection to user provided URL...');
136-
// console.log('leaving ipcMain.on connect.')
137-
// })
138-
// .catch((error) => {
139-
// console.log(` Error in connect, failed to load application : ${error}`)
140-
// // return false;
141-
// })
142106
}
107+
}catch(err){
108+
console.log('Error connecting to databse: ', err);
109+
}
110+
});
111+
// console.log(` Error in connect, failed to load application : ${error}`)
143112

144-
//LOCAL INSTANCE: SETTINGS.JSON
145-
else {
146113

147-
const fileContents = JSON.parse(fs.readFileSync(settingsLocation, 'utf8'));
148-
const userDatabase = fileContents[username].services[index];
149-
// We get index from sidebar container: which is the mapplication (DEMO)
150-
const [databaseType, URI] = [userDatabase[1], userDatabase[2]];
114+
// ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, index: number, URI: string) => {
115+
// try {
116+
// // const isConnected = mongoose.connection.readyState === 1;
117+
// // if (isConnected){
118+
// // console.log('Connection to MongoDb has already been established.');
119+
// // } else {
120+
121+
// // }
122+
// // Extract databaseType and URI from settings.json at particular index
123+
// // get index from application context
124+
125+
// // Connect to User database instantiated in 'dashboard.ts'
126+
// if (username !== 'guest') {
127+
128+
// const isConnected = mongoose.connection.readyState === 1;
129+
// if (isConnected){
130+
// console.log('Connection to MongoDb has already been established.');
131+
// message.sender.send('databaseConnected', 'connection already established.');
132+
// } else {
133+
// return User.findOne({ username: username })
134+
// .then(async (data) => {
135+
// console.log('Hi, inside ipcMain.on connect in data.ts! Establishing connection to user provided database URI');
136+
// const databaseType = data.services[index][1]
137+
// const appURI = data.services[index][2]
138+
// console.log('database type', databaseType);
139+
// console.log('appURI', appURI);
140+
// if (databaseType === 'MongoDB') {
141+
// const shouldbedb = await connectMongo(index, appURI);
142+
// // console.log(shouldbedb);
143+
// // await connectMongo()
144+
// currentDatabaseType = databaseType;
145+
// message.sender.send('databaseConnected', 'connected!');
146+
// } else if (databaseType === 'SQL') {
147+
// pool = await connectPostgres(index, appURI);
148+
// currentDatabaseType = databaseType;
149+
// message.sender.send('databaseConnected', 'connected!');
150+
// }
151+
// console.log('Established connection to user provided URL...');
152+
// console.log('leaving ipcMain.on connect.')
153+
// })
154+
// .catch((error) => {
155+
// console.log(` Error in connect, failed to load application : ${error}`)
156+
// // return false;
157+
// })
158+
// }
159+
160+
// // const MONGO_URI = URI
161+
// // mongoose.connect(MONGO_URI, {
162+
// // useNewUrlParser: true,
163+
// // useUnifiedtopology: true,
164+
// // })
165+
// // test().catch((error) => console.log('error in second db', error));
166+
// // async function test() {
167+
// // const db2 = await mongoose.createConnection('mongodb+srv://seconddbtest:[email protected]/?retryWrites=true&w=majority');
168+
// // console.log('connection to user provided db established..');
169+
// // }
170+
// // Check for existing user in DB, if found, connect to load application based on database type
171+
// // return User.findOne({ username: username })
172+
// // .then(async (data) => {
173+
// // console.log('Hi, inside ipcMain.on connect in data.ts! Establishing connection to user provided database URI');
174+
// // const databaseType = data.services[index][1]
175+
// // const appURI = data.services[index][2]
176+
// // console.log('database type', databaseType);
177+
// // console.log('appURI', appURI);
178+
// // if (databaseType === 'MongoDB') {
179+
// // const shouldbedb = await connectMongo(index, appURI);
180+
// // // console.log(shouldbedb);
181+
// // // await connectMongo()
182+
// // currentDatabaseType = databaseType;
183+
// // message.sender.send('databaseConnected', 'connected!');
184+
// // } else if (databaseType === 'SQL') {
185+
// // pool = await connectPostgres(index, appURI);
186+
// // currentDatabaseType = databaseType;
187+
// // message.sender.send('databaseConnected', 'connected!');
188+
// // }
189+
// // console.log('Established connection to user provided URL...');
190+
// // console.log('leaving ipcMain.on connect.')
191+
// // })
192+
// // .catch((error) => {
193+
// // console.log(` Error in connect, failed to load application : ${error}`)
194+
// // // return false;
195+
// // })
196+
// }
197+
198+
// //LOCAL INSTANCE: SETTINGS.JSON
199+
// else {
200+
201+
// const fileContents = JSON.parse(fs.readFileSync(settingsLocation, 'utf8'));
202+
// const userDatabase = fileContents[username].services[index];
203+
// // We get index from sidebar container: which is the mapplication (DEMO)
204+
// const [databaseType, URI] = [userDatabase[1], userDatabase[2]];
151205

152-
console.log('if guest, inputted URI here...', URI)
153-
// Connect to the proper database
154-
if (databaseType === 'MongoDB') await connectMongo(index,URI);
155-
if (databaseType === 'SQL') pool = await connectPostgres(index, URI);
206+
// console.log('if guest, inputted URI here...', URI)
207+
// // Connect to the proper database
208+
// if (databaseType === 'MongoDB') await connectMongo(index,URI);
209+
// if (databaseType === 'SQL') pool = await connectPostgres(index, URI);
156210

157-
// Currently set to a global variable
158-
currentDatabaseType = databaseType;
211+
// // Currently set to a global variable
212+
// currentDatabaseType = databaseType;
159213

160-
message.sender.send('databaseConnected', 'connected!');
161-
// eslint-disable-next-line no-shadow
162-
}
163-
} catch ({ message }) {
164-
console.log('Error in "connect" event', message);
165-
}
166-
});
214+
// message.sender.send('databaseConnected', 'connected!');
215+
// // eslint-disable-next-line no-shadow
216+
// }
217+
// } catch ({ message }) {
218+
// console.log('Error in "connect" event', message);
219+
// }
220+
// });
167221

168222
/**
169223
* @event serviceRequest/serviceResponse
@@ -173,7 +227,18 @@ ipcMain.on('servicesRequest', async (message: Electron.IpcMainEvent) => {
173227
try {
174228
let result: any;
175229
console.log('Hi, inside data.ts - servicesRequest function. Fetching services...');
230+
231+
console.log('Testing ServicesModel!');
232+
ServicesModel.find()
233+
.then(data => {
234+
console.log('Testing ServicesModel. Here is the data being sent to front end: ', data);
235+
result = data;
236+
message.sender.send('servicesResponse', JSON.stringify(result));
237+
})
238+
.catch(err => console.log('error fetching services'));
239+
176240
// Mongo Database
241+
// console.log('CurrentDataBase TYPE:', currentDatabaseType);
177242
if (currentDatabaseType === 'MongoDB' ) {
178243
// Get all documents from the services collection
179244
result = await ServicesModel.find();
@@ -187,9 +252,9 @@ ipcMain.on('servicesRequest', async (message: Electron.IpcMainEvent) => {
187252
result = result.rows;
188253
}
189254

190-
console.log('Sending servicesResponse to frontend with the following result:', result);
255+
// console.log('Sending servicesResponse to frontend with the following result:', result);
191256
// Async event emitter - send response
192-
message.sender.send('servicesResponse', JSON.stringify(result));
257+
// message.sender.send('servicesResponse', JSON.stringify(result));
193258
// eslint-disable-next-line no-shadow
194259
} catch ({ message }) {
195260
console.log('Error in "servicesRequest" event', message);

0 commit comments

Comments
 (0)