Skip to content

Commit 9670831

Browse files
committed
incorporated mongoose.connection for already established connections to databases. Works for when database instances are the same, but not when two different mongo db databses have been provided. Added additional comments for flow between application context, occupied, serviceModal, and data.ts to help developers understand flow of information and state
1 parent 416caae commit 9670831

File tree

6 files changed

+91
-34
lines changed

6 files changed

+91
-34
lines changed

app/components/Login.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ const Login = React.memo(() => {
1414
* Function that will be called when the form button is clicked
1515
* It handles submitting the login information
1616
*/
17-
17+
// v10: ipcRenderer returning a string with the response of user mode (light or dark).
18+
// There is currently no redirection after failed login.
1819
const handleSubmit = (e: any) => {
1920
e.preventDefault();
2021
const inputFields: HTMLInputElement[] = e.currentTarget.querySelectorAll('input');
@@ -24,7 +25,8 @@ const Login = React.memo(() => {
2425
// inputFields.forEach(input => (input.value = ''));
2526
const response: boolean | string = ipcRenderer.sendSync('login', { username, password });
2627
if (typeof (response) === 'string') {
27-
console.log('response', response)
28+
console.log('Hi, login successful and response string (mode) is:', response);
29+
console.log('Redirected to Occupied from Login.');
2830
setUser(username);
2931
setMode(response);
3032
navigate('/');

app/components/Occupied.tsx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,10 @@ interface StyleProps {
5555
}
5656
type ClickEvent = React.MouseEvent<HTMLElement>;
5757

58+
//v10: Memoized function, witouth any props. Should theoretically be called only once.
5859
const Occupied = React.memo(() => {
60+
console.log('Hi, inside Occupied. Memoize function invoked');
61+
5962
const { awsData, fetchAwsData, fetchAwsAppInfo, setLoadingState } = useContext(AwsContext);
6063
const { setServicesData, app, setApp } = useContext(ApplicationContext);
6164
const { user, applications, getApplications, deleteApp, mode } = useContext(DashboardContext);
@@ -76,7 +79,9 @@ const Occupied = React.memo(() => {
7679
const navigate = useNavigate();
7780

7881
// Grab services and applications whenever the user changes
82+
// v10: Runs once when Occupied is memoized, and subsequently when user is updated.
7983
useEffect(() => {
84+
console.log('Hi, inside Occupied.ts useEffect function.');
8085
setServicesData([]);
8186
getApplications();
8287
}, [user]);
@@ -91,6 +96,8 @@ const Occupied = React.memo(() => {
9196
};
9297

9398
// Handle clicks on Application cards
99+
// v10 info: when card is clicked (not on the delete button) if the service is an AWS instance,
100+
// you are redirected to AWSGraphsContainer passing in the state object containing typeOfService
94101
const handleClick = (
95102
event: ClickEvent,
96103
selectedApp: string,
@@ -106,9 +113,13 @@ const Occupied = React.memo(() => {
106113
selectedService === 'AWS/EKS'
107114
) {
108115
setAppIndex(i);
116+
// setApp is never invoked, function is not established?
109117
setApp(selectedApp);
110118
navigate(`/aws/:${app}`, { state: { typeOfService: selectedService } });
111119
} else {
120+
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(i, ' ', selectedApp, ' ', 'N/A ', serviceModalOpen );
112123
setAppIndex(i);
113124
setApp(selectedApp);
114125
setServicesData([]);

app/context/ApplicationContext.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
5555
* 4. Remove the listener for `servicesResponse`
5656
* @param application - application name
5757
*/
58+
// v10: Invoked by connectToDB, passing in app (card title)
5859
const fetchServicesNames = useCallback((application: string) => {
59-
console.log('app when fetch services name', application);
60+
console.log('Hi, inside ApplicationConext - fetchServicesNames callback. Sending servicesRequest to ipcMain.');
61+
console.log('app when fetch services name (not sure if necesarry)', application);
6062
// setApp(application);
6163

6264
ipcRenderer.send('servicesRequest');
@@ -66,7 +68,9 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
6668
// Parse JSON data into object
6769
if (tryParseJSON(data)) result = JSON.parse(data);
6870
console.log('result from ipcrenderer services response is: ', result);
71+
console.log('Calling setServicesData passing in above result. Current servicesData is the following: ', servicesData);
6972
setServicesData(result);
73+
console.log('Leaving fetchedServicesNames function.');
7074
ipcRenderer.removeAllListeners('servicesResponse');
7175
});
7276
}, []);
@@ -76,9 +80,10 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
7680
* creates an event emitter that connects to the user provided URI for the service (should be the database URI...)
7781
* v10 notes: seems to only be set up for local instances, not when a cloud based service is clicked, causes an issue since a user provided
7882
* database should not exist...
83+
* @params application - is the name of the card taht was clicked on
7984
*/
8085
const connectToDB = useCallback((username: string, index: number, application: string, URI: string) => {
81-
86+
console.log('Hi, inside ApplicationContext, connectToDB function was invoked.');
8287
ipcRenderer.removeAllListeners('databaseConnected');
8388
ipcRenderer.send('connect', username, index, URI);
8489
ipcRenderer.on('databaseConnected', (event: Electron.Event, data: any) => {

app/modals/ServicesModal.tsx

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@ interface IService {
1818
}
1919

2020
// v10: Seems to never have been updated for cloud-based info...
21-
// applications[i][2] refers to the local instance URI
21+
// servicesModal is re-rendered depending on i and application passed in...
2222
const ServicesModal: React.FC<ServicesModalProps> = React.memo(({ i, app }) => {
2323
console.log('Hi, inside ServicesModal. Memoize function invoked in ServicesModal.');
24+
console.log('ServicesModal current props (index, app): ', i, ' ', app);
2425

2526
const { user, applications } = useContext(DashboardContext);
2627
console.log('user from Dashboard Context:', user);
@@ -38,9 +39,13 @@ const ServicesModal: React.FC<ServicesModalProps> = React.memo(({ i, app }) => {
3839
}
3940
};
4041

41-
// note: connectToDB function definition in Application Context. Used
42+
// v10: connectToDB function definition in Application Context.
43+
// 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
4245
useEffect(() => {
43-
console.log('Hi, inside ServicesModal - connectToDB');
46+
console.log('Hi, inside useEffect in ServicesModal. Calling connectToDB function.');
47+
console.log("Passing the following parameters for user, i, app, applications, ");
48+
console.log(user, ' ', i, ' ', app, ' ', applications);
4449
connectToDB(user, i, app, applications[i][2]);
4550
}, [i]);
4651

electron/routes/dashboard.ts

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ ipcMain.handle(
338338
);
339339

340340
ipcMain.on('login', (message: IpcMainEvent, user: { username: string; password: string }) => {
341+
console.log('Hi, inside ipcMain(login) call in dashboard.ts!');
341342
const { username, password } = user;
342343

343344
// Load in the stored users
@@ -350,16 +351,18 @@ ipcMain.on('login', (message: IpcMainEvent, user: { username: string; password:
350351
// message.returnValue = false;
351352
// return;
352353
// }
353-
console.log('in login')
354354

355355
return User.findOne({ username : username })
356356
.then((data) => {
357357
// console.log('data', data)
358358
console.log(data.username, ' is being logged in...');
359359
if (data !== null && bcrypt.compareSync(password, data.password)) {
360-
console.log('User found');
361-
// console.log('found data', data.mode)
360+
console.log('Login was successful.');
361+
console.log('returned data: ', data);
362+
console.log('found data', data.mode);
362363
currentUser = username
364+
365+
// returnValue being set to mode, returned as string.
363366
message.returnValue = data.mode
364367
return message.returnValue;
365368
} else {
@@ -373,14 +376,6 @@ ipcMain.on('login', (message: IpcMainEvent, user: { username: string; password:
373376
// return false;
374377
})
375378

376-
377-
378-
379-
380-
381-
382-
383-
384379
});
385380

386381
ipcMain.on('signOut', (message: IpcMainEvent) => {

electron/routes/data.ts

Lines changed: 55 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -59,26 +59,26 @@ const settingsLocation = path.resolve(__dirname, '../../settings.json');
5959
*/
6060
ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, index: number, URI: string) => {
6161
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+
// }
6268
// Extract databaseType and URI from settings.json at particular index
6369
// get index from application context
6470

6571
// Connect to User database instantiated in 'dashboard.ts'
6672
if (username !== 'guest') {
67-
68-
// const MONGO_URI = URI
69-
// mongoose.connect(MONGO_URI, {
70-
// useNewUrlParser: true,
71-
// useUnifiedtopology: true,
72-
// })
73-
// test().catch((error) => console.log('error in second db', error));
74-
// async function test() {
75-
// const db2 = await mongoose.createConnection('mongodb+srv://seconddbtest:[email protected]/?retryWrites=true&w=majority');
76-
// console.log('connection to user provided db established..');
77-
// }
78-
// Check for existing user in DB, if found, connect to load application based on database type
79-
return User.findOne({ username: username })
73+
74+
const isConnected = mongoose.connection.readyState === 1;
75+
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 })
8080
.then(async (data) => {
81-
console.log('Hi, inside ipcMain.on connect in data.ts! User db is working, testing second db.');
81+
console.log('Hi, inside ipcMain.on connect in data.ts! Establishing connection to user provided database URI');
8282
const databaseType = data.services[index][1]
8383
const appURI = data.services[index][2]
8484
console.log('database type', databaseType);
@@ -94,13 +94,52 @@ ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, i
9494
currentDatabaseType = databaseType;
9595
message.sender.send('databaseConnected', 'connected!');
9696
}
97+
console.log('Established connection to user provided URL...');
9798
console.log('leaving ipcMain.on connect.')
9899
})
99100
.catch((error) => {
100101
console.log(` Error in connect, failed to load application : ${error}`)
101102
// return false;
102103
})
103104
}
105+
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+
// })
142+
}
104143

105144
//LOCAL INSTANCE: SETTINGS.JSON
106145
else {
@@ -133,7 +172,7 @@ ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, i
133172
ipcMain.on('servicesRequest', async (message: Electron.IpcMainEvent) => {
134173
try {
135174
let result: any;
136-
console.log('Hi, inside data.ts - servicesRequest.');
175+
console.log('Hi, inside data.ts - servicesRequest function. Fetching services...');
137176
// Mongo Database
138177
if (currentDatabaseType === 'MongoDB' ) {
139178
// Get all documents from the services collection
@@ -148,7 +187,7 @@ ipcMain.on('servicesRequest', async (message: Electron.IpcMainEvent) => {
148187
result = result.rows;
149188
}
150189

151-
console.log('Sending the following result to frontend:', result);
190+
console.log('Sending servicesResponse to frontend with the following result:', result);
152191
// Async event emitter - send response
153192
message.sender.send('servicesResponse', JSON.stringify(result));
154193
// eslint-disable-next-line no-shadow

0 commit comments

Comments
 (0)