Skip to content

Commit 93c1d41

Browse files
authored
Merge pull request #9 from oslabs-beta/subscription
Added comment and cleaned up code
2 parents 5932215 + 7838e9d commit 93c1d41

File tree

11 files changed

+76
-75
lines changed

11 files changed

+76
-75
lines changed

main.js

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -519,8 +519,3 @@ ipcMain.on('stop-mock-server', () => {
519519
console.log('No mock server to kill');
520520
}
521521
});
522-
523-
ipcMain.on('error', (event, errorMessage) => {
524-
console.log(errorMessage);
525-
dialog.showErrorBox('Title', errorMessage);
526-
});

main_process/main_trpcController.js

Lines changed: 39 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,19 @@ const { ipcMain } = require('electron');
55
const trpcController = {
66
makeFetch: async function (event, reqRes, get, post) {
77
try {
8+
// wrap it in a try catch block so if anything goes wrong we can just send the error to the front end instead of having no response
89
reqRes.timeSent = Date.now();
10+
//these will contain data about the response that we will get back from our get/post request
911
const cookies = [];
1012
const getHeaders = {};
1113
const postHeaders = {};
1214
const events = [];
1315

14-
const reqArr = [get, post];
16+
const reqArr = [get, post]; // our array of request, put into an array in order to use promise.all easier
1517
const resArr = await Promise.all(
1618
reqArr.map((req) => {
1719
if (req) {
20+
// only make a request if it exists
1821
return fetch(req.url, {
1922
// credentials: req.credentials,
2023
// mode: req.mode,
@@ -26,12 +29,14 @@ const trpcController = {
2629
...(req.body && { body: JSON.stringify(req.body) }),
2730
});
2831
} else {
29-
return Promise.resolve(false);
32+
return Promise.resolve(false); //if it doesnt exist we can simply return false
3033
}
3134
})
3235
);
3336
reqRes.timeReceived = Date.now();
3437
resArr.forEach((res, index) => {
38+
// here we will combine cookies recieved from both request into one array, however we will seperate out the header by post/get request
39+
// was sleep-deprived should have also seperate cookie into get/post cookie
3540
if (res) {
3641
const headersResponse = res.headers.raw();
3742
if (headersResponse['set-cookie']) {
@@ -54,27 +59,31 @@ const trpcController = {
5459
});
5560

5661
const resData = await Promise.all(
62+
//if there was a response we will parse it if not we will just return it (which is just the value of false)
5763
resArr.map((res) => {
5864
return res ? res.json() : res;
5965
})
6066
);
61-
console.dir(resData, { depth: null });
67+
//attach meta data about the response onto the reqRes object to send back to front end
6268
resData.forEach((res) => events.push(res));
6369
reqRes.response.cookies = cookies;
6470
reqRes.response.events = events;
6571
reqRes.response.headers = [getHeaders, postHeaders];
6672
reqRes.connection = 'closed';
6773
reqRes.connectionType = 'plain';
68-
event.sender.send('reqResUpdate', reqRes);
74+
event.sender.send('reqResUpdate', reqRes); //send object back to front end
6975
} catch (error) {
76+
//if error we will push the error into event to be display
7077
reqRes.connection = 'error';
7178
reqRes.error = error;
7279
reqRes.response.events.push(error);
73-
event.sender.send('reqResUpdate', reqRes);
80+
event.sender.send('reqResUpdate', reqRes); // send updated object back to front end
7481
}
7582
},
7683
parseOptionForFetch(reqResObject, method, procedures) {
84+
// this method using the data attach to the response property to construct an object that we could use to easily make the neccessary request
7785
function parseString(str) {
86+
//this function is use to parse user inputted argument from json into javascript
7887
if (str === 'true') {
7988
return true;
8089
}
@@ -99,34 +108,27 @@ const trpcController = {
99108
return JSON.parse(str);
100109
}
101110
}
102-
const { headers, cookie } = reqResObject.request;
111+
const { headers, cookie } = reqResObject.request; //grab the headers and cookie inputted by user
103112

104-
const formattedHeaders = {};
113+
const formattedHeaders = {}; //header object
105114
headers.forEach((head) => {
106115
if (head.active) {
107116
formattedHeaders[head.key] = head.value;
108117
}
109118
});
110119
if (cookie) {
120+
//parses cookie data to attach to option object
111121
cookie.forEach((cookie) => {
112122
const cookieString = `${cookie.key}=${cookie.value}`;
113123
// attach to formattedHeaders so options object includes this
114-
115124
formattedHeaders.cookie = formattedHeaders.cookie
116125
? formattedHeaders.cookie + ';' + cookieString
117126
: cookieString;
118127
});
119128
}
120129

121-
const outputObj = {
122-
method,
123-
mode: 'cors', // no-cors, cors, *same-origin
124-
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
125-
credentials: 'include', // include, *same-origin, omit
126-
headers: formattedHeaders,
127-
redirect: 'follow', // manual, *follow, error
128-
referrer: 'no-referrer', // no-referrer, *client
129-
};
130+
// here we will construct the url and the body using data inside the reqRes obj
131+
// because a user could batch procedures together/ we need to account for the request object to contain data for both a get request and a post request
130132
let url = '';
131133
const body = {};
132134
procedures.forEach((procedure, index) => {
@@ -148,34 +150,43 @@ const trpcController = {
148150
'?batch=1' +
149151
`&input=${encodeURIComponent(JSON.stringify(body))}`;
150152
}
151-
outputObj.url = url;
153+
154+
const outputObj = {
155+
// the main object that will get returned
156+
url,
157+
method,
158+
mode: 'cors', // no-cors, cors, *same-origin
159+
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
160+
credentials: 'include', // include, *same-origin, omit
161+
headers: formattedHeaders,
162+
redirect: 'follow', // manual, *follow, error
163+
referrer: 'no-referrer', // no-referrer, *client
164+
};
152165
return outputObj;
153166
},
154167

155168
openRequest: async function (event, reqRes) {
156-
// const reqRes = Object.assign({}, reqResOriginal);
157-
// reqRes.response = Object.assign({}, reqRes.response);
158-
const procedures = reqRes.request.procedures;
169+
const procedures = reqRes.request.procedures; // grabbing all of the procedures out of the reqRes object
170+
171+
//filter the procedures into either query or mutate in order to make the appropriate http request for each procedure
172+
// all query procedure will be made with a get request
173+
// all mutation procedure will be made with a post request
159174
const getReq = procedures.filter(
160175
(procedure) => procedure.method === 'QUERY'
161176
);
162177
const postReq = procedures.filter(
163178
(procedure) => procedure.method === 'MUTATE'
164179
);
165180

181+
// parsing data from the reqRes object to construct either a get/post option object that contains everything we need to make our get/post http request
166182
const getOption = getReq.length
167183
? this.parseOptionForFetch(reqRes, 'GET', getReq)
168184
: false;
169185
const postOption = postReq.length
170186
? this.parseOptionForFetch(reqRes, 'POST', postReq)
171187
: false;
172188

173-
const updatedReqRes = await this.makeFetch(
174-
event,
175-
reqRes,
176-
getOption,
177-
postOption
178-
);
189+
this.makeFetch(event, reqRes, getOption, postOption); // where we will finally make the request inside of makeFetch
179190
},
180191
cookieFormatter(cookieArray) {
181192
return cookieArray.map((eachCookie) => {
@@ -201,3 +212,4 @@ module.exports = () => {
201212
trpcController.openRequest(event, reqResObj);
202213
});
203214
};
215+

src/client/components/main/TRPC-composer/TRPCComposer.tsx

Lines changed: 22 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import SendRequestButton from '../sharedComponents/requestButtons/SendRequestBut
66
import TRPCMethodAndEndpointEntryForm from './TRPCMethodAndEndpointEntryForm';
77
// Import Redux hooks
88
import { useSelector, useDispatch } from 'react-redux';
9-
// Import Actions from RTK slice
109

10+
// Import Actions from RTK slice
1111
import historyController from '../../../controllers/historyController';
1212
import connectionController from '../../../controllers/reqResController';
1313

@@ -26,15 +26,23 @@ import { responseDataSaved } from '../../../toolkit-refactor/slices/reqResSlice'
2626
*/
2727

2828
const PROCEDURE_DEFAULT = {
29-
method: 'QUERY',
30-
endpoint: '',
31-
variable: '',
29+
//the default format for whenever a new prcedure get add
30+
method: 'QUERY', // the type of method either query or mutate
31+
endpoint: '', // endpoint for this specific procedure
32+
variable: '', // argument that is to be attach to this procedure
3233
};
3334

34-
// {type:"",payload:{index,value}}
35+
//************** reducer function******************** */
36+
// this function is used to manage the main state of this component which is an array of procedures [{method,endpoint,variable}]
37+
// it will take in the old state (array of procedures) as well as an action object where the type will dictate which action will get trigger
38+
// The action object wil also contain the index as well as the new value for the procedure that is being manipulated (all inside of action.payload)
39+
// after its done manipulating the state it will return the updated array that will be use as the new procedures state
40+
41+
//********************************** */
3542

3643
function reducer(procedures, action) {
3744
if (action.type === 'METHOD') {
45+
//
3846
const proceduresCopy = [...procedures];
3947
const procedure = proceduresCopy[action.payload.index];
4048
const newState = {
@@ -74,17 +82,20 @@ function reducer(procedures, action) {
7482
}
7583

7684
export default function TRPCComposer(props) {
77-
const dispatch = useDispatch();
85+
const dispatch = useDispatch(); // dispatch for main redux store
7886

79-
const [showSubscription, setShowSubscription] = useState(false);
87+
const [showSubscription, setShowSubscription] = useState(false); // manage subscription component
8088
const subscriptionHandler = (bool) => {
8189
setShowSubscription(bool);
8290
};
91+
8392
const [procedures, proceduresDipatch] = useReducer(reducer, [
93+
//userReducer hook to manage the main state (the array of procedures)
8494
PROCEDURE_DEFAULT,
8595
]);
8696

8797
const {
98+
//grabbing all neccessary information to build a new reqRes object from the main redux store through props drilling
8899
newRequestFields,
89100
newRequestFields: {
90101
gRPC,
@@ -121,38 +132,12 @@ export default function TRPCComposer(props) {
121132
const newRequest = useSelector((state: RootState) => state.newRequest);
122133

123134
const addProcedures = () => {
135+
// reducer dispatch for adding a new procedure to the procedures array
124136
proceduresDipatch({ type: 'ADD' });
125137
};
126138

127-
const dispatchTRPCResponse = (tRPCResponse) => {
128-
const newCurrentResponse: any = {
129-
checkSelected: false,
130-
checked: false,
131-
connection: 'closed',
132-
connectionType: 'plain',
133-
createdAt: new Date(),
134-
gRPC: false,
135-
graphQL: false,
136-
host: requestFields.url,
137-
id: uuid(),
138-
minimized: false,
139-
path: '/',
140-
protoPath: undefined,
141-
protocol: 'http://',
142-
request: { ...newRequest },
143-
tab: undefined,
144-
timeReceived: null,
145-
timeSent: null,
146-
url: requestFields.url,
147-
webrtc: false,
148-
response: {
149-
events: [tRPCResponse],
150-
},
151-
};
152-
dispatch(responseDataSaved(newCurrentResponse));
153-
};
154-
155139
const sendRequest = async () => {
140+
// THE MAIN FUNCTION to both compose the main reqRes object as well as sending it to the back end
156141
const id = uuid();
157142
const headers = newRequest.newRequestHeaders.headersArr.filter(
158143
(x) => x.active
@@ -199,11 +184,9 @@ export default function TRPCComposer(props) {
199184
historyController.addHistoryToIndexedDb(reqRes);
200185
reqResItemAdded(reqRes);
201186

202-
//reset for next request
203-
// composerFieldsReset();
204-
// connectionController.openReqRes(reqRes.id);
187+
// saving the reqRes object to the array of reqRes managed by the redux store
205188
dispatch(responseDataSaved(reqRes));
206-
connectionController.openReqRes(reqRes.id);
189+
connectionController.openReqRes(reqRes.id); // passing the reqRes object to the connectionController inside of reqRes controller
207190
};
208191

209192
return (

src/client/components/main/TRPC-composer/TRPCMethodAndEndpointEntryForm.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const TRPCMethodAndEndpointEntryForm = () => {
1414
const dispatch = useDispatch();
1515

1616
const urlChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
17+
//update global redux store everytime user make changes to url
1718
const url: string = e.target.value;
1819

1920
dispatch(

src/client/components/main/TRPC-composer/TRPCPrceduresEndPoint.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const TRPCPrceduresEndPoint = (props) => {
2222
return () => document.removeEventListener('click', closeDropdown);
2323
}, []);
2424

25+
/// these functions exists to dispatch function to the reducer function inside of main trpc composer file.
2526
const methodHandler = (method) => {
2627
props.proceduresDipatch({
2728
type: 'METHOD',
@@ -116,3 +117,4 @@ const TRPCPrceduresEndPoint = (props) => {
116117
};
117118

118119
export default TRPCPrceduresEndPoint;
120+

src/client/components/main/TRPC-composer/TRPCProcedure.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import TRPCVariableForm from './TRPCVariableForm';
33
import TRPCPrceduresEndPoint from './TRPCPrceduresEndPoint';
44

55
export default function TRPCProcedure(props) {
6+
//renders each procedure
67
return (
78
<div style={container}>
89
<TRPCPrceduresEndPoint
@@ -24,3 +25,4 @@ const container = {
2425
border: '1px solid black',
2526
padding: '10px 0px',
2627
};
28+

src/client/components/main/TRPC-composer/TRPCProceduresContainer.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import React from 'react';
22
import TRPCProcedure from './TRPCProcedure';
33

44
export default function TRPCProceduresContainer(props) {
5+
//renders all of the procedures inside the procedures array
56
const proceduresJSX = props.procedures.map((procedure, index) => {
67
return (
78
<TRPCProcedure
@@ -25,3 +26,4 @@ const h3Styles = {
2526
fontSize: '1.17em',
2627
fontWeight: 'bold',
2728
};
29+

src/client/components/main/TRPC-composer/TRPCSubscriptionContainer.tsx

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export default function TRPCSubscriptionContainer(props) {
2525
};
2626
let sub;
2727
const startSubscription = async () => {
28+
setsubscriptionStarted(true);
2829
try {
2930
const wsClient = createWSClient({
3031
url: link,
@@ -58,11 +59,10 @@ export default function TRPCSubscriptionContainer(props) {
5859
});
5960
},
6061
});
61-
setsubscriptionStarted(true);
62+
6263
setResponseBody(`Subscription at ${endpoint} started`);
6364
} catch (e) {
64-
console.log(e);
65-
api.send('error', JSON.stringify(e));
65+
setResponseBody(JSON.stringify(e));
6666
}
6767
};
6868
const endSubscription = () => {
@@ -138,3 +138,4 @@ const h3Styles = {
138138
fontSize: '1.17em',
139139
fontWeight: 'bold',
140140
};
141+

src/client/components/main/TRPC-composer/TRPCVariableForm.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import { useSelector } from 'react-redux';
44
import { vscodeDark } from '@uiw/codemirror-theme-vscode';
55

66
export default function TRPCVariableForm(props) {
7+
// input for for user to attach argument with their procedures
78
const isDark = useSelector((store: any) => store.ui.isDark);
89
const onChangeHandler = (string) => {
10+
// this function dispatch action to the main reducer function inside of trpc composer
911
props.proceduresDipatch({
1012
type: 'VARIABLE',
1113
payload: { index: props.index, value: string },
@@ -25,3 +27,4 @@ export default function TRPCVariableForm(props) {
2527
</div>
2628
);
2729
}
30+

src/client/components/main/response-composer/EventsContainer.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ function EventsContainer({ currentResponse }: EventsContainerProps) {
3434
}
3535
const { events, headers } = response;
3636
let responseBody = '';
37+
//check if its a trpc response
3738
if (currentResponse.trpc) {
3839
events.forEach((event: any, idx: number) => {
3940
if (event) {

0 commit comments

Comments
 (0)