Skip to content

[UNI-196] feat : 길찾기 결과 경로 없음 에러(422) 화면 및 커스텀 훅 추가 #109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { NavigationRouteList } from "../../data/types/route";
import useRoutePoint from "../../hooks/useRoutePoint";
import { formatDistance } from "../../utils/navigation/formatDistance";
import { Link } from "react-router";
import useUniversityInfo from "../../hooks/useUniversityInfo";
import { useQueryClient } from "@tanstack/react-query";

const TITLE = "전동휠체어 예상소요시간";

Expand All @@ -21,12 +23,20 @@ const NavigationDescription = ({ isDetailView, navigationRoute }: TopBarProps) =
const { origin, destination } = useRoutePoint();
const { totalCost, totalDistance, hasCaution } = navigationRoute;

const { university } = useUniversityInfo();
const queryClient = useQueryClient();

/** 지도 페이지로 돌아가게 될 경우, 캐시를 삭제하기 */
const removeQuery = () => {
queryClient.removeQueries({ queryKey: ['fastRoute', university?.id, origin?.nodeId, destination?.nodeId] })
}

Comment on lines +30 to +33
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

함수로 분리한 점 좋은 것 같습니다!

return (
<div className="w-full p-5">
<div className={`w-full flex flex-row items-center ${isDetailView ? "justify-start" : "justify-between"}`}>
<span className="text-left text-kor-body3 text-primary-500 flex-1 font-semibold">{TITLE}</span>
{!isDetailView && (
<Link to="/map">
<Link to="/map" onClick={removeQuery}>
<Cancel />
</Link>
)}
Expand Down
8 changes: 8 additions & 0 deletions uniro_frontend/src/constant/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,16 @@ export class BadRequestError extends Error {
}
}

export class UnProcessableError extends Error {
constructor(message: string) {
super(message);
this.name = "UnProcessable";
}
}

Comment on lines +15 to +21
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확장성이 좋은 것 같습니다 굳~

export enum ERROR_STATUS {
NOT_FOUND = 404,
BAD_REQUEST = 400,
INTERNAL_ERROR = 500,
UNPROCESSABLE = 422,
}
2 changes: 1 addition & 1 deletion uniro_frontend/src/hooks/useMutationError.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default function useMutationError<TData, TError, TVariables, TContext>(
else throw error;

return (
<div className="fixed inset-0 flex items-center justify-center bg-[rgba(0,0,0,0.2)]">
<div className="fixed inset-0 flex items-center justify-center bg-[rgba(0,0,0,0.2)] z-100">
< div className="w-full max-w-[365px] flex flex-col bg-gray-100 rounded-400 overflow-hidden" >
<div className="flex flex-col justify-center space-y-1 py-[25px]">
<p className="text-kor-body1 font-bold text-system-red">{title.mainTitle}</p>
Expand Down
92 changes: 92 additions & 0 deletions uniro_frontend/src/hooks/useQueryError.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { QueryClient, useQuery, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
import { NotFoundError, BadRequestError, ERROR_STATUS, UnProcessableError } from "../constant/error";
import { useEffect, useState } from "react";

type Fallback = {
[K in Exclude<ERROR_STATUS, ERROR_STATUS.INTERNAL_ERROR>]?: {
mainTitle: string;
subTitle: string[];
};
};

type HandleError = {
fallback: Fallback;
onClose?: () => void;
}

type UseQueryErrorReturn<TData, TError> = [
React.FC,
UseQueryResult<TData, TError>
];

export default function useQueryError<TQueryFnData, TError, TData>(
options: UseQueryOptions<TQueryFnData, TError, TData>,
queryClient?: QueryClient,
handleSuccess?: () => void,
handleError?: HandleError,
): UseQueryErrorReturn<TData, TError> {
const [isOpen, setOpen] = useState<boolean>(false);
const result = useQuery<TQueryFnData, TError, TData, readonly unknown[]>(options, queryClient);

const { isError, error, status } = result;

useEffect(() => {
setOpen(isError)
}, [isError])

/** 페이지 이동하여도 status는 success로 남아있으므로 필요시, removeQueries하여 캐시 삭제 */
/** 추가적인 로직 고민하기 */
useEffect(() => {
if (status === "success" && handleSuccess) handleSuccess();
}, [status])

const close = () => {
if (handleError?.onClose) handleError?.onClose();
setOpen(false);
}

const Modal: React.FC = () => {
if (!isOpen || !handleError || !error) return null;

const { fallback } = handleError;

let title: { mainTitle: string, subTitle: string[] } = {
mainTitle: "",
subTitle: [],
}

if (error instanceof NotFoundError) {
title = fallback[404] ?? title;
}
else if (error instanceof BadRequestError) {
title = fallback[400] ?? title;
}
else if (error instanceof UnProcessableError) {
title = fallback[422] ?? title;
}

else throw error;

return (
<div className="fixed inset-0 flex items-center justify-center bg-[rgba(0,0,0,0.2)] z-100">
< div className="w-full max-w-[365px] flex flex-col bg-gray-100 rounded-400 overflow-hidden" >
<div className="flex flex-col justify-center space-y-1 py-[25px]">
<p className="text-kor-body1 font-bold text-system-red">{title.mainTitle}</p>
<div className="space-y-0">
{title.subTitle.map((_subtitle, index) =>
<p key={`error-modal-subtitle-${index}`} className="text-kor-body3 font-regular text-gray-700">{_subtitle}</p>)}
</div>
</div>
<button
onClick={close}
className="h-[58px] border-t-[1px] border-gray-200 text-kor-body2 font-semibold active:bg-gray-200"
>
확인
</button>
</div >
</div >
)
}

return [Modal, result];
}
35 changes: 31 additions & 4 deletions uniro_frontend/src/pages/map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { RoutePoint } from "../constant/enum/routeEnum";
import { Markers } from "../constant/enum/markerEnum";
import createAdvancedMarker, { createUniversityMarker } from "../utils/markers/createAdvanedMarker";
import toggleMarkers from "../utils/markers/toggleMarkers";
import { Link } from "react-router";
import { useNavigate } from "react-router";
import useModal from "../hooks/useModal";
import ReportModal from "../components/map/reportModal";
import useUniversityInfo from "../hooks/useUniversityInfo";
Expand All @@ -28,9 +28,11 @@ import { CautionIssueType, DangerIssueType, MarkerTypes } from "../data/types/en
import { CautionIssue, DangerIssue } from "../constant/enum/reportEnum";

/** API 호출 */
import { useSuspenseQueries } from "@tanstack/react-query";
import { useQuery, useSuspenseQueries } from "@tanstack/react-query";
import { getAllRisks } from "../api/routes";
import { getAllBuildings } from "../api/nodes";
import { getNavigationResult } from "../api/route";
import useQueryError from "../hooks/useQueryError";

export type SelectedMarkerTypes = {
type: MarkerTypes;
Expand Down Expand Up @@ -68,8 +70,32 @@ export default function MapPage() {
const { university } = useUniversityInfo();
useRedirectUndefined<University | undefined>([university]);

const navigate = useNavigate();
if (!university) return;

const [FailModal, { status, data, refetch: findFastRoute }] = useQueryError({
queryKey: ['fastRoute', university.id, origin?.nodeId, destination?.nodeId],
queryFn: () => getNavigationResult(university.id, origin ? origin?.nodeId : -1, destination ? destination?.nodeId : -1),
enabled: false,
retry: 0,
},
undefined,
() => { navigate('/result') },
{
fallback: {
400: {
mainTitle: "잘못된 요청입니다.", subTitle: ["새로고침 후 다시 시도 부탁드립니다."]
},
404: {
mainTitle: "해당 경로를 찾을 수 없습니다.", subTitle: ["해당 건물이 길이랑 연결되지 않았습니다."]
},
422: {
mainTitle: "해당 경로를 찾을 수 없습니다.", subTitle: ["위험 요소 버튼을 클릭하여,", "통행할 수 없는 원인을 파악하실 수 있습니다."]
}
}
}
Comment on lines +77 to +96
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

캐시로 빠른 길를 넘겨주는 것, 좋은 것 같습니다

)

const results = useSuspenseQueries({
queries: [
{ queryKey: [university.id, "risks"], queryFn: () => getAllRisks(university.id) },
Expand Down Expand Up @@ -495,9 +521,9 @@ export default function MapPage() {
</BottomSheet>
{origin && destination && origin.nodeId !== destination.nodeId ? (
/** 출발지랑 도착지가 존재하는 경우 길찾기 버튼 보이기 */
<Link to="/result" className="absolute bottom-6 space-y-2 w-full px-4">
<div onClick={() => findFastRoute()} className="absolute bottom-6 space-y-2 w-full px-4">
<Button variant="primary">길찾기</Button>
</Link>
</div>
) : (
/** 출발지랑 도착지가 존재하지 않거나, 같은 경우 기존 Button UI 보이기 */
<>
Expand All @@ -511,6 +537,7 @@ export default function MapPage() {
</>
)}
{isOpen && <ReportModal close={close} />}
<FailModal />
</div>
);
}
4 changes: 3 additions & 1 deletion uniro_frontend/src/utils/fetch/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BadRequestError, NotFoundError } from "../../constant/error";
import { BadRequestError, NotFoundError, UnProcessableError } from "../../constant/error";

export default function Fetch() {
const baseURL = import.meta.env.VITE_REACT_SERVER_BASE_URL;
Expand All @@ -17,6 +17,8 @@ export default function Fetch() {
throw new BadRequestError("Bad Request");
} else if (response.status === 404) {
throw new NotFoundError("Not Found");
} else if (response.status === 422) {
throw new UnProcessableError("UnProcessable");
} else {
throw new Error("UnExpected Error");
}
Expand Down