Skip to content

Commit 4c19b02

Browse files
committed
리펙토링
1 parent 02bb1d7 commit 4c19b02

39 files changed

+351
-208
lines changed

src/pages/Classroom/Classroom.tsx

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -116,38 +116,45 @@ const Classroom = () => {
116116
};
117117

118118
const useSSE = (url: string) => {
119-
const [data, setData] = useState(null);
119+
const [data, setData] = useState<unknown>(null);
120120
const queryClient = useQueryClient();
121121

122122
const subscribe = useCallback(() => {
123123
const eventSource = new EventSource(url, { withCredentials: true });
124124

125125
eventSource.onmessage = (event) => {
126-
const newData = JSON.parse(event.data);
127-
setData(newData);
128-
// setQueryData로 값 캐싱
129-
queryClient.setQueryData(["sse-data"], newData);
130-
guestDataRefetch();
131-
classroomDataRefetch();
126+
try {
127+
const newData = JSON.parse(event.data);
128+
setData(newData);
129+
queryClient.setQueryData(["sse-data"], newData);
130+
guestDataRefetch();
131+
classroomDataRefetch();
132+
} catch (error) {
133+
console.error("Failed to parse SSE message:", error);
134+
}
132135
};
136+
133137
eventSource.addEventListener("action", (event) => {
134-
const newData = JSON.parse(event.data);
135-
setData(newData);
136-
// setQueryData로 값 캐싱
137-
queryClient.setQueryData(["sse-data", classroomId], newData);
138+
try {
139+
const newData = JSON.parse(event.data);
140+
setData(newData);
141+
queryClient.setQueryData(["sse-data", classroomId], newData);
142+
guestDataRefetch();
143+
classroomDataRefetch();
144+
} catch (error) {
145+
console.error("Failed to parse SSE action event:", error);
146+
}
147+
});
138148

139-
guestDataRefetch();
140-
classroomDataRefetch();
149+
eventSource.addEventListener("error", (error) => {
150+
console.error("SSE connection error:", error);
141151
});
142-
// connection되면
143-
eventSource.addEventListener("open", function () {});
144152

145153
return () => {
146154
eventSource.close();
147155
};
148-
}, [url, queryClient]);
156+
}, [url, queryClient, classroomId, guestDataRefetch, classroomDataRefetch]);
149157

150-
// 요청을 끊을 때 일어나는 useEffect
151158
useEffect(() => {
152159
const unsubscribe = subscribe();
153160
return unsubscribe;

src/pages/Visualization/Visualization.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { useEditorStore } from "@/store/editor";
2020
import { useGptTooltipStore } from "@/store/gptTooltip";
2121

2222
export default function Visualization() {
23-
const [code, setCode] = useState<any>(
23+
const [code, setCode] = useState<string>(
2424
[
2525
"for i in range(2, 10):\n" +
2626
" for j in range(1, 10):\n" +

src/pages/Visualization/VisualizationClassroom.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ interface ClassAccessRightDataType {
3535
// 원본 코드 타입 정의
3636

3737
const VisualizationClassroom = () => {
38-
const [code, setCode] = useState<any>(
38+
const [code, setCode] = useState<string>(
3939
[
4040
"for i in range(2, 10):\n" +
4141
" for j in range(1, 10):\n" +

src/pages/Visualization/components/RightSection/hooks/processors/processCodeFlow.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { WhileDto } from "@/pages/Visualization/types/dto/whileDto";
66
import { PrintItem } from "@/pages/Visualization/types/codeFlow/printItem";
77
import { InputItem } from "@/pages/Visualization/types/codeFlow/inputItem";
88
import { CodeFlowVariableItem } from "@/pages/Visualization/types/codeFlow/codeFlowVariableItem";
9-
import { State } from "../../types";
9+
import { State, CodeFlowItem } from "../../types";
1010
import { createObjectToAdd } from "../../services/createObjectToAdd";
1111
import { updateCodeFlow } from "../../services/updateCodeFlow";
1212
import { refreshCodeFlow } from "../../services/refreshCodeFlow";
@@ -73,8 +73,7 @@ export const processCodeFlow = ({
7373
}
7474
}
7575

76-
// CodeFlow 업데이트 또는 추가
77-
let changedCodeFlows: any[];
76+
let changedCodeFlows: CodeFlowItem[];
7877
if (newUsedId.includes(toAddObject.id!)) {
7978
// 기존 항목 업데이트
8079
if (toAddObject.type === "for" || toAddObject.type === "while") {

src/pages/Visualization/components/RightSection/hooks/processors/processEndUserFunc.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { EndUserFuncDto } from "@/pages/Visualization/types/dto/endUserFuncDto";
2-
import { State } from "../../types";
2+
import { State, CodeFlowItem } from "../../types";
33
import { createObjectToAdd } from "../../services/createObjectToAdd";
44
import { deleteCodeFlow } from "../../services/deleteCodeFlow";
55
import { insertIntoDepth } from "../../services/insertIntoDepth";
@@ -48,7 +48,7 @@ export const processEndUserFunc = ({
4848
const deletedCodeFlow = deleteCodeFlow(accCodeFlow.objects, preprocessedCode.id);
4949
let newAccCodeFlow = { objects: deletedCodeFlow };
5050

51-
let finallyCodeFlow: any;
51+
let finallyCodeFlow: CodeFlowItem[];
5252
if (toAddObject.depth > prevTrackingDepth) {
5353
finallyCodeFlow = insertIntoDepth(newAccCodeFlow.objects, toAddObject, prevTrackingId);
5454
} else if (toAddObject.depth === prevTrackingDepth) {

src/pages/Visualization/components/RightSection/hooks/processors/processIfElseDefine.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { IfElseDto } from "@/pages/Visualization/types/dto/ifElseDto";
2-
import { State } from "../../types";
2+
import { State, CodeFlowItem } from "../../types";
33
import { createObjectToAdd } from "../../services/createObjectToAdd";
44
import { turnOffAllNodeLight } from "../../services/turnOffAllNodeLight";
55
import { insertIntoDepth } from "../../services/insertIntoDepth";
@@ -45,7 +45,7 @@ export const processIfElseDefine = ({
4545

4646
newUsedId.push(toAddObject.id!);
4747

48-
let finallyCodeFlow: any;
48+
let finallyCodeFlow: CodeFlowItem[];
4949
if (toAddObject.depth > newTrackingDepth) {
5050
finallyCodeFlow = insertIntoDepth(newAccCodeFlow.objects, toAddObject, newTrackingId);
5151
} else if (toAddObject.depth === newTrackingDepth) {

src/pages/Visualization/components/RightSection/hooks/processors/utils.ts

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,51 +2,51 @@ import { WrapperDataStructureItem } from "@/pages/Visualization/types/dataStruct
22
import { VariablesDto } from "@/pages/Visualization/types/dto/variablesDto";
33
import { AppendDto } from "@/pages/Visualization/types/dto/appendDto";
44
import { CreateCallStackDto } from "@/pages/Visualization/types/dto/createCallStackDto";
5+
import { ValidTypeDto } from "@/pages/Visualization/types/dto/ValidTypeDto";
56
import { unLightCodeFlow } from "../../services/unLightCodeFlow";
67
import { State } from "../../types";
78

89
export const resetDataStructuresLight = (accDataStructures: WrapperDataStructureItem): WrapperDataStructureItem => {
910
return Object.entries(accDataStructures).reduce((acc, [key, value]) => {
1011
acc[key] = {
11-
data: value.data.map((structure) => ({
12-
...structure,
13-
})),
12+
data: value.data,
1413
isLight: false,
1514
};
1615
return acc;
1716
}, {} as WrapperDataStructureItem);
1817
};
1918

19+
const initializeLightStructure = (toLightStructures: Record<string, string[]>, callStackName: string): void => {
20+
if (!toLightStructures[callStackName]) {
21+
toLightStructures[callStackName] = [];
22+
}
23+
};
24+
2025
export const calculateToLightStructures = (
21-
preprocessedCode: any,
26+
preprocessedCode: ValidTypeDto,
2227
accCodeFlow: State
2328
): { toLightStructures: Record<string, string[]>; accCodeFlow: State } => {
2429
const toLightStructures: Record<string, string[]> = {};
2530
let newAccCodeFlow = accCodeFlow;
31+
const codeType = preprocessedCode.type.toLowerCase();
2632

27-
if (preprocessedCode.type.toLowerCase() === "assign") {
33+
if (codeType === "assign") {
2834
const code = preprocessedCode as VariablesDto;
2935
code.variables?.forEach((element) => {
30-
const callStackName = code.callStackName;
31-
if (!toLightStructures[callStackName]) {
32-
toLightStructures[callStackName] = [];
33-
}
34-
toLightStructures[callStackName].push(element.name);
36+
initializeLightStructure(toLightStructures, code.callStackName);
37+
toLightStructures[code.callStackName].push(element.name);
3538
});
36-
} else if (preprocessedCode.type.toLowerCase() === "append") {
39+
} else if (codeType === "append") {
3740
const code = preprocessedCode as AppendDto;
3841
const variable = code.variable;
3942
if (variable.type.toLowerCase() === "variable") {
4043
toLightStructures[code.callStackName] = [variable.name];
4144
}
42-
} else if (preprocessedCode.type.toLowerCase() === "createCallStack") {
45+
} else if (codeType === "createcallstack") {
4346
const code = preprocessedCode as CreateCallStackDto;
4447
code.args?.forEach((element) => {
45-
const callStackName = code.callStackName;
46-
if (!toLightStructures[callStackName]) {
47-
toLightStructures[callStackName] = [];
48-
}
49-
toLightStructures[callStackName].push(element.name);
48+
initializeLightStructure(toLightStructures, code.callStackName);
49+
toLightStructures[code.callStackName].push(element.name);
5050
});
5151
const unLightaccCodeFlow = unLightCodeFlow(accCodeFlow.objects);
5252
newAccCodeFlow = { objects: unLightaccCodeFlow };

src/pages/Visualization/components/RightSection/hooks/useCodeExecutionMutation.ts

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { PreprocessedCodesContext } from "../../../context/PreProcessedCodesCont
77
import { InputErrorContext } from "@/pages/Visualization/context/InputErrorContext";
88
import { useContext } from "react";
99
import { ApiError } from "../types";
10+
import { handleExecutionError } from "../utils/errorHandler";
1011

1112
export const useCodeExecutionMutation = () => {
1213
const { openAlert } = useCustomAlert();
@@ -35,35 +36,18 @@ export const useCodeExecutionMutation = () => {
3536
setPreprocessedCodes([]);
3637
setCodeFlowLength(0);
3738
setStepIdx(0);
38-
setConsoleList([data.result.output]);
39+
setConsoleList([data.result.output || ""]);
3940
setHighlightLines([]);
4041
},
4142
onError(error: ApiError) {
42-
console.error(error);
43-
44-
if (error.message === "데이터 형식이 올바르지 않습니다") {
45-
return;
46-
} else if (error.code === "CA-400006" || error.code === "CA-400999") {
47-
openAlert("지원하지 않는 코드가 포함되어 있습니다");
48-
return;
49-
} else if (error.code === "CA-400005") {
50-
setIsInputError(true);
51-
openAlert("입력된 input의 갯수가 적습니다.");
52-
} else if (error.code === "CA-400002") {
53-
// 잘못된 문법 에러처리
54-
const linNumber = Number(error.result.lineNumber);
55-
const errorMessage = error.result.errorMessage;
56-
if (errorMessage) {
57-
setErrorLine({ lineNumber: linNumber, message: errorMessage });
58-
setConsoleList([errorMessage]);
59-
}
60-
setPreprocessedCodes([]);
61-
return;
62-
} else if (error.code === "CA-400007") {
63-
openAlert("코드의 실행 횟수가 너무 많습니다.");
64-
return;
65-
}
66-
setConsoleList([]);
43+
handleExecutionError({
44+
error,
45+
openAlert,
46+
setPreprocessedCodes,
47+
setConsoleList,
48+
setErrorLine,
49+
setIsInputError,
50+
});
6751
},
6852
});
6953
};

src/pages/Visualization/components/RightSection/hooks/useCodeVisualizationMutation.ts

Lines changed: 9 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { useContext } from "react";
1010
import { isNotServiceDtoType } from "../services/isNotServiceDtoType";
1111
import { isValidTypeDtoArray } from "@/pages/Visualization/types/dto/ValidTypeDto";
1212
import { SuccessResponse, ApiError } from "../types";
13+
import { handleVisualizationError } from "../utils/errorHandler";
1314

1415
interface UseCodeVisualizationMutationProps {
1516
setIsPlaying: (value: boolean) => void;
@@ -38,9 +39,7 @@ export const useCodeVisualizationMutation = ({ setIsPlaying }: UseCodeVisualizat
3839
return useMutation<SuccessResponse, ApiError, Parameters<typeof visualize>[0]>({
3940
mutationFn: visualize,
4041
async onSuccess(data) {
41-
// 타입 체크 함수
4242
if (isNotServiceDtoType(data.result.code)) {
43-
console.error("시각화를 지원하지 않는 코드가 포함되어 있습니다.");
4443
throw new Error("시각화를 지원하지 않는 코드가 포함되어 있습니다.");
4544
}
4645
if (isValidTypeDtoArray(data.result.code)) {
@@ -49,39 +48,18 @@ export const useCodeVisualizationMutation = ({ setIsPlaying }: UseCodeVisualizat
4948
setDisplayNone(false);
5049
setIsPlaying(true);
5150
} else {
52-
console.error("데이터 형식이 올바르지 않습니다");
5351
throw new Error("데이터 형식이 올바르지 않습니다");
5452
}
5553
},
5654
onError(error) {
57-
console.error(error);
58-
59-
if (error.message === "데이터 형식이 올바르지 않습니다") {
60-
return;
61-
} else if (error.code === "CA-400006" || error.code === "CA-400999") {
62-
openAlert("지원하지 않는 코드가 포함되어 있습니다.");
63-
return;
64-
} else if (error.code === "CA-400005") {
65-
setIsInputError(true);
66-
openAlert("입력된 input의 개수가 적습니다.");
67-
} else if (error.message === "시각화를 지원하지 않는 코드가 포함되어 있습니다.") {
68-
openAlert("시각화를 지원하지 않는 코드가 포함되어 있습니다.");
69-
return;
70-
} else if (error.code === "CA-400002") {
71-
const linNumber = Number(error.result.lineNumber);
72-
const errorMessage = error.result.errorMessage;
73-
if (errorMessage) {
74-
setErrorLine({ lineNumber: linNumber, message: errorMessage });
75-
setConsoleList([errorMessage]);
76-
}
77-
setPreprocessedCodes([]);
78-
return;
79-
} else if (error.code === "CA-400007") {
80-
openAlert("코드의 실행 횟수가 너무 많습니다.");
81-
return;
82-
}
83-
setConsoleList([]);
84-
setPreprocessedCodes([]);
55+
handleVisualizationError({
56+
error,
57+
openAlert,
58+
setPreprocessedCodes,
59+
setConsoleList,
60+
setErrorLine,
61+
setIsInputError,
62+
});
8563
},
8664
});
8765
};

src/pages/Visualization/components/RightSection/hooks/usePreprocessedCodesProcessor.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,6 @@ export const usePreprocessedCodesProcessor = () => {
104104
const state = createInitialState();
105105

106106
for (const preprocessedCode of preprocessedCodes) {
107-
console.log(preprocessedCode);
108-
109-
// whiledefine 타입은 건너뛰기
110107
if (preprocessedCode.type.toLowerCase() === "whiledefine") {
111108
continue;
112109
}

0 commit comments

Comments
 (0)