Skip to content

Commit 826b9be

Browse files
committed
cleaned up electron backend code.
1 parent 1a5e127 commit 826b9be

File tree

8 files changed

+59
-176
lines changed

8 files changed

+59
-176
lines changed

app/components/Occupied.tsx

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

58+
// type OccupiedProps = {
59+
// switch: any;
60+
// setSwitch: any;
61+
// };
62+
5863
//v10: Memoized function, witouth any props. Should theoretically be called only once.
5964
const Occupied = React.memo(() => {
6065
console.log('Hi, inside Occupied. Memoize function invoked');
6166

6267
const { awsData, fetchAwsData, fetchAwsAppInfo, setLoadingState } = useContext(AwsContext);
6368
const { setServicesData, app, setApp } = useContext(ApplicationContext);
69+
// const { user, getApplications, deleteApp, mode } = useContext(DashboardContext);
6470
const { user, applications, getApplications, deleteApp, mode } = useContext(DashboardContext);
6571
const { commsData } = useContext(CommsContext);
6672
const [serviceModalOpen, setServiceModalOpen] = useState<boolean>(false);
@@ -87,6 +93,7 @@ const Occupied = React.memo(() => {
8793
getApplications();
8894
}, [user]);
8995

96+
9097
// Dynamic refs
9198
const delRef = useRef<any>([]);
9299

app/containers/MainContainer.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ import AwsGraphsContainer from '../containers/AWSGraphsContainer';
1414
import '../stylesheets/MainContainer.scss';
1515

1616
const MainContainer = React.memo(() => {
17-
const { mode } = useContext(DashboardContext);
17+
const { mode, applications } = useContext(DashboardContext);
1818
const currentModeCSS = mode === 'light' ? lightAndDark.lightModeMain : lightAndDark.darkModeMain;
19-
19+
2020
return (
2121
<>
2222
<div className="main-container" style={currentModeCSS}>

app/context/ApplicationContext.tsx

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,16 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
5858
// v10: Invoked by connectToDB, passing in app (card title)
5959
const fetchServicesNames = useCallback((application: string) => {
6060
console.log('Hi, inside ApplicationConext - fetchServicesNames callback. Sending servicesRequest to ipcMain.');
61-
console.log('app when fetch services name (not sure if necesarry)', application);
61+
console.log('app when fetch services name: ', application);
6262
// setApp(application);
6363

6464
ipcRenderer.send('servicesRequest');
6565

6666
ipcRenderer.on('servicesResponse', (event: Electron.Event, data: any) => {
6767
let result: any;
6868
// Parse JSON data into object
69-
if (tryParseJSON(data)) result = JSON.parse(data);
69+
// if (tryParseJSON(data)) result = JSON.parse(data);
70+
result = JSON.parse(data);
7071
console.log('result from ipcrenderer services response is: ', result);
7172
console.log('Calling setServicesData passing in above result. Current servicesData is the following: ', servicesData);
7273
setServicesData(result);
@@ -82,10 +83,10 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
8283
* database should not exist...
8384
* @params application - is the name of the card taht was clicked on
8485
*/
85-
const connectToDB = useCallback((username: string, index: number, application: string, URI: string) => {
86+
const connectToDB = useCallback((username: string, index: number, application: string, URI: string, databaseType: string) => {
8687
console.log('Hi, inside ApplicationContext, connectToDB function was invoked.');
8788
ipcRenderer.removeAllListeners('databaseConnected');
88-
ipcRenderer.send('connect', username, index, URI);
89+
ipcRenderer.send('connect', username, index, URI, databaseType);
8990
ipcRenderer.on('databaseConnected', (event: Electron.Event, data: any) => {
9091
fetchServicesNames(application);
9192
});

app/context/DashboardContext.tsx

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,24 +42,29 @@ const DashboardContextProvider = React.memo((props: any) => {
4242
const children = props.children;
4343

4444
// Initial user will always be the guest
45-
const [user, setUser] = useState('guest');
46-
const [applications, setApplications] = useState<string[]>([]);
45+
const [user, setUser] = useState<string>('guest');
46+
const [applications, setApplications] = useState<string[][]>([]);
4747
const [mode, setMode] = useState<string>('light');
4848

49+
4950
const getApplications = useCallback(() => {
5051
const result = ipcRenderer.sendSync('getApps');
5152
setApplications(result);
5253
}, []);
5354

5455
const addApp = useCallback((fields: IFields) => {
5556
const { typeOfService, database, URI, name, description } = fields;
57+
const newApp = [name, database, URI, description, typeOfService];
5658
console.log('what is the service that was passed into add app: ', typeOfService)
5759
const result = ipcRenderer.sendSync(
5860
'addApp',
5961
JSON.stringify([name, database, URI, description, typeOfService])
6062
);
6163
setApplications(result);
62-
console.log('the current application that was added is : ', result)
64+
// console.log('applications: ', applications);
65+
// console.log('new app to add: ', newApp);
66+
// setApplications([...applications, newApp]);
67+
// console.log('the current application that was added is : ', result);
6368
}, []);
6469

6570
const addAwsApp = useCallback((awsFields: AwsFields) => {

app/modals/AddModal.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ interface IFields {
1313

1414
interface IDashboard {
1515
addApp: (fields: IFields) => void;
16+
setApplications: any;
1617
}
1718

1819
interface AddModalProps {
@@ -23,7 +24,7 @@ type InputElement = React.ChangeEvent<HTMLSelectElement | HTMLInputElement | HTM
2324
type FormElement = React.FormEvent<HTMLFormElement>;
2425

2526
const AddModal: React.FC<AddModalProps> = React.memo(({ setOpen }) => {
26-
const { addApp }: IDashboard = useContext(DashboardContext);
27+
const { addApp, setApplications }: IDashboard = useContext(DashboardContext);
2728

2829
const [fields, setFields] = useState<IFields>({
2930
typeOfService: 'Docker',
@@ -36,6 +37,8 @@ const AddModal: React.FC<AddModalProps> = React.memo(({ setOpen }) => {
3637
// Submit form data and save to database
3738
const handleSubmit = (event: FormElement) => {
3839
event.preventDefault();
40+
// const newApp = [name, database, URI, description, typeOfService];
41+
// setApplications(prev => [...prev, ...newApp])
3942
addApp(fields);
4043
setOpen(false); // Close modal on submit
4144
};

app/modals/ServicesModal.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,12 @@ const ServicesModal: React.FC<ServicesModalProps> = React.memo(({ i, app }) => {
4242
// v10: connectToDB function definition in Application Context.
4343
// parameters for connectToDB call: user, i (index), app (card title), app URL (url on card)
4444
// applications[i][2] refers to the user provided URI
45+
// adding database type to make connection and fetchServiceNames more efficient
4546
useEffect(() => {
4647
console.log('Hi, inside useEffect in ServicesModal. Calling connectToDB function.');
4748
console.log("Passing the following parameters for user, i, app, applications, ");
48-
console.log(user, ' ', i, ' ', app, ' ', applications);
49-
connectToDB(user, i, app, applications[i][2]);
49+
console.log(user, ' ', i, ' ', app, ' ', applications, applications[i][1]);
50+
connectToDB(user, i, app, applications[i][2], applications[i][1]);
5051
}, [i]);
5152

5253

electron/models/UserModel.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// const MONGO_URI = 'mongodb+srv://chronoslany:[email protected]/?retryWrites=true&w=majority';
21
const MONGO_URI = 'mongodb+srv://seconddbtest:[email protected]/?retryWrites=true&w=majority';
32
// import mongoose, { Schema, Document } from 'mongoose';
43

electron/routes/data.ts

Lines changed: 30 additions & 163 deletions
Original file line numberDiff line numberDiff line change
@@ -58,166 +58,42 @@ const settingsLocation = path.resolve(__dirname, '../../settings.json');
5858
* is accessed in info.commsData and info.healthData
5959
*/
6060

61-
ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, index: number, URI: string) => {
61+
ipcMain.on('connect', async (message: Electron.IpcMainEvent, username: string, index: number, URI: string, databaseType: string) => {
6262

6363
try{
64-
const isConnected = mongoose.connection.readyState === 1;
65-
if (isConnected){
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-
82-
message.sender.send('databaseConnected', 'connected!');
83-
})
84-
.catch(error => {
85-
console.log('Error connecting to MongoDB inside data.ts connection:', error);
86-
});
87-
}
88-
});
89-
} else {
64+
// set database type from parameter
65+
currentDatabaseType = databaseType;
66+
console.log('Database type: ', databaseType);
67+
if(currentDatabaseType === 'MongoDB'){
68+
// First check if there is already an established mongoose connection with another databse...
69+
const isConnected = mongoose.connection.readyState === 1;
70+
if (isConnected){
71+
console.log('A connection to a mongoDB has already been established. Closing connection.');
72+
mongoose.connection.close((error) => {
73+
if(error) {
74+
console.log('Error closing mongoDB connection: ', error);
75+
}
76+
});
77+
}
9078
console.log('Database connection not found. Establishing connection...');
91-
// Connect to the proper database
92-
mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true })
93-
.then(() => {
79+
// Connect to the proper database
80+
mongoose.connect(URI, { useNewUrlParser: true, useUnifiedTopology: true })
81+
.then(() => {
9482
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-
10083
message.sender.send('databaseConnected', 'connected!');
101-
})
102-
.catch(error => {
103-
console.log('Error connecting to MongoDB inside data.ts connection:', error);
104-
});
105-
106-
}
107-
}catch(err){
84+
})
85+
.catch(error => {
86+
console.log('Error connecting to MongoDB inside data.ts connection:', error);
87+
});
88+
} else if (currentDatabaseType === 'SQL'){
89+
// has not been reconfigured to handle different requests to SQL databses.
90+
pool = await connectPostgres(index, URI);
91+
message.sender.send('databaseConnected', 'connected!');
92+
}
93+
} catch(err){
10894
console.log('Error connecting to databse: ', err);
10995
}
11096
});
111-
// console.log(` Error in connect, failed to load application : ${error}`)
112-
113-
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]];
205-
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);
210-
211-
// // Currently set to a global variable
212-
// currentDatabaseType = databaseType;
213-
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-
// });
22197

22298
/**
22399
* @event serviceRequest/serviceResponse
@@ -228,17 +104,8 @@ ipcMain.on('servicesRequest', async (message: Electron.IpcMainEvent) => {
228104
let result: any;
229105
console.log('Hi, inside data.ts - servicesRequest function. Fetching services...');
230106

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-
240107
// Mongo Database
241-
// console.log('CurrentDataBase TYPE:', currentDatabaseType);
108+
console.log('CurrentDataBase TYPE:', currentDatabaseType);
242109
if (currentDatabaseType === 'MongoDB' ) {
243110
// Get all documents from the services collection
244111
result = await ServicesModel.find();
@@ -254,7 +121,7 @@ ipcMain.on('servicesRequest', async (message: Electron.IpcMainEvent) => {
254121

255122
// console.log('Sending servicesResponse to frontend with the following result:', result);
256123
// Async event emitter - send response
257-
// message.sender.send('servicesResponse', JSON.stringify(result));
124+
message.sender.send('servicesResponse', JSON.stringify(result));
258125
// eslint-disable-next-line no-shadow
259126
} catch ({ message }) {
260127
console.log('Error in "servicesRequest" event', message);

0 commit comments

Comments
 (0)