Skip to content
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
73 changes: 73 additions & 0 deletions src/app/error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"use client";

import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import Button from "@/components/Button";
import Sidebar from "@/components/Sidebar";
import TopBar from "@/components/TopBar";
import { commonError } from "@/lib/loadError";

// Figma W-E3 · W-E4
export default function LoadError({
error,
retry,
}: {
error: unknown;
retry: () => void;
}) {
// 화면이 뜬 뒤에 연결이 돌아와도 안내가 바뀌지 않게 처음 값을 쓴다
const [kind] = useState(() => commonError(error));
const queryClient = useQueryClient();

// 다시 시도하거나 다른 메뉴로 갔다 오면 실패한 요청을 다시 보내게 한다
// 실패한 쿼리를 지워 두면 다음에 그 화면이 뜰 때 새로 요청한다
useEffect(() => {
queryClient.removeQueries({
predicate: (q) => q.state.status === "error" && !q.getObserversCount(),
});
}, [queryClient]);

// 요청 실패가 아닌 에러(화면 버그)는 Next 기본 오류 화면에 맡긴다
if (kind === undefined) throw error;

return (
<div className="flex h-screen gap-4 p-4">
<Sidebar />
<div className="flex min-w-0 flex-1 flex-col gap-4">
<TopBar title="오류" />
<main className="flex flex-1 p-2">
<div
role="alert"
className="glass flex flex-1 flex-col items-center justify-center gap-3 rounded-xl [--glass-from:0.78] [--glass-to:0.4] px-8 py-12"
>
<span
aria-hidden
className="bg-sunken text-display-md text-fg-secondary flex size-12 items-center justify-center rounded-full"
>
!
</span>
<h2 className="text-title-lg">
{kind === "offline"
? "인터넷 연결이 끊겼어요"
: "일시적인 오류가 생겼어요"}
</h2>
<p className="text-body text-fg-secondary text-center">
{kind === "offline" ? (
"연결을 확인한 뒤 다시 시도해 주세요."
) : (
<>
서버가 응답하지 않아요. 잠시 후 다시 시도해 주세요.
<br />
계속되면 개발팀에 알려 주세요 · 오류 코드 {kind}
</>
)}
</p>
<Button type="button" onClick={() => retry()}>
다시 시도
</Button>
</div>
</main>
</div>
</div>
);
}
4 changes: 2 additions & 2 deletions src/features/dashboard/queries.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { useQuery } from "@tanstack/react-query";
import { loadQuery } from "@/lib/loadError";
import { getStats } from "./api";

export const useStats = () =>
useQuery({
queryKey: ["admin", "stats"],
queryFn: getStats,
// 실패하면 기다리지 않고 바로 오류 화면을 띄운다. 다시 시도는 화면의 버튼으로 한다
retry: false,
...loadQuery,
// 화면 문구("10분마다 갱신")와 맞춘다
refetchInterval: 10 * 60 * 1000,
});
48 changes: 48 additions & 0 deletions src/features/guides/components/GuidesError.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import Button from "@/components/Button";

// Figma W-4g
// shortcut: 목록과 가이드를 한 번에 불러와서 실패하면 종 목록은 비워 둔다, 따로 불러오게 되면 시안처럼 목록을 보여 줌
export default function GuidesError({ onRetry }: { onRetry: () => void }) {
return (
<div className="flex flex-1 gap-4 p-2">
<section className="glass flex w-60 shrink-0 flex-col rounded-xl [--glass-angle:107deg] [--glass-from:0.78] [--glass-to:0.4] px-3 py-4.5">
<h2 className="text-button px-2.5">종 선택</h2>
</section>
<section className="glass flex min-w-0 flex-1 flex-col gap-3.5 rounded-xl [--glass-angle:126deg] [--glass-from:0.78] [--glass-to:0.4] px-6 py-5.5">
<h2 className="text-display-md">가이드</h2>
<div
role="alert"
className="flex h-90 shrink-0 flex-col items-center justify-center gap-3 rounded-xl border border-white px-8 py-12"
>
<span
aria-hidden
className="bg-sunken text-display-md text-fg-secondary flex size-12 items-center justify-center rounded-full"
>
!
</span>
<p className="text-title-lg">가이드를 불러오지 못했어요</p>
<p className="text-body text-fg-secondary">
잠시 후 다시 시도해 주세요. 저장된 가이드는 그대로예요.
</p>
<Button type="button" onClick={onRetry}>
다시 불러오기
</Button>
</div>
<div className="mt-auto flex items-center gap-2.5">
<p className="text-caption text-fg-tertiary flex-1">
불러오지 못했어요
</p>
<Button variant="ghost" disabled className="w-20">
되돌리기
</Button>
<Button disabled className="w-14.5">
저장
</Button>
</div>
</section>
<aside className="w-80 shrink-0">
<h2 className="text-button">앱 카드 미리보기</h2>
</aside>
</div>
);
}
7 changes: 5 additions & 2 deletions src/features/guides/components/GuidesManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ import { sections, type Content, type Guide, type Section } from "../data";
import { useGuides, useSaveGuide } from "../queries";
import AppCardPreview from "./AppCardPreview";
import GuideEditor from "./GuideEditor";
import GuidesError from "./GuidesError";
import SpeciesList from "./SpeciesList";

export default function GuidesManager() {
const { data } = useGuides();
// shortcut: 불러오는 중·실패 화면은 시안이 없어 비워 둔다, 시안 나오면 추가
const { data, isError, refetch } = useGuides();
// 이미 받은 목록이 있으면 갱신이 실패해도 편집 화면(고치던 내용)을 그대로 둔다
if (isError && !data) return <GuidesError onRetry={() => refetch()} />;
// shortcut: 불러오는 중 화면은 시안이 없어 비워 둔다, 시안 나오면 추가
return data?.length ? <Editor guides={data} /> : null;
}

Expand Down
6 changes: 3 additions & 3 deletions src/features/guides/queries.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { loadQuery } from "@/lib/loadError";
import { fetchGuides, saveGuide } from "./api";
import type { Content, Guide } from "./data";

export const useGuides = () =>
useQuery({
queryKey: ["guides"],
queryFn: fetchGuides,
// 대시보드(useStats)처럼 실패하면 기다리지 않고 바로 실패로 둔다.
// 다시 시도하면 종 수만큼 요청이 또 나가는 것도 막는다
retry: false,
// 자동 재시도가 없어 종 수만큼 요청이 또 나가는 것도 막는다
...loadQuery,
// 창에 돌아오거나 화면에 다시 들어올 때마다 종 수만큼 다시 불러오지 않게 5분은 새것으로 본다
staleTime: 5 * 60 * 1000,
});
Expand Down
52 changes: 35 additions & 17 deletions src/features/species/components/SpeciesManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import SpeciesTable, { type Species } from "./SpeciesTable";
type Editing = { target?: Species; draft: Partial<Species>; error?: string };

export default function SpeciesManager() {
const { data: species } = useSpecies();
const { data, isError, refetch } = useSpecies();
const { mutateAsync: saveSpecies, isPending: saving } = useSaveSpecies();
const { mutateAsync: setHidden, isPending: hiddenPending } = useSetHidden();
const [query, setQuery] = useState("");
Expand All @@ -29,8 +29,10 @@ export default function SpeciesManager() {
return () => clearTimeout(id);
}, [toast]);

// shortcut: 불러오는 중·실패 화면은 시안이 없어 비워 둔다 (가이드 화면과 같음), 시안 나오면 추가
if (!species) return null;
// shortcut: 불러오는 중 화면은 시안이 없어 비워 둔다 (가이드 화면과 같음), 시안 나오면 추가
if (!data && !isError) return null;
const failed = !data;
const species = data ?? [];

const q = query.trim();
const rows = q ? species.filter((s) => s.name.includes(q)) : species;
Expand Down Expand Up @@ -96,9 +98,11 @@ export default function SpeciesManager() {
<div className="flex items-center gap-3">
<div className="flex-1">
<h2 className="text-title-lg">
{q
? `종 목록 · 검색 결과 ${rows.length}종`
: `종 목록 · ${species.length}종`}
{failed
? "종 목록"
: q
? `종 목록 · 검색 결과 ${rows.length}종`
: `종 목록 · ${species.length}종`}
</h2>
<p className="text-caption text-fg-tertiary mt-0.5">
저장하면 앱의 종 선택 목록에 바로 반영돼요 · 숨긴 종은 회색으로
Expand All @@ -113,17 +117,31 @@ export default function SpeciesManager() {
onEdit={(s) => setEditing({ target: s, draft: s })}
onToggleHidden={toggleHidden}
empty={
<div className="flex flex-1 flex-col items-center justify-center gap-2.5">
<p className="text-title-lg">
&apos;{q}&apos;와 맞는 종이 없어요
</p>
<p className="text-body text-fg-secondary">
철자를 확인하거나 새 종으로 추가해 주세요.
</p>
<Button onClick={() => setEditing({ draft: { name: q } })}>
+ {q} 종 추가
</Button>
</div>
failed ? (
// Figma W-3j
<div
role="alert"
className="flex flex-1 flex-col items-center justify-center gap-2.5"
>
<p className="text-title-lg">종 목록을 불러오지 못했어요</p>
<p className="text-body text-fg-secondary">
잠시 후 다시 시도해 주세요. 계속되면 개발팀에 알려 주세요.
</p>
<Button onClick={() => refetch()}>다시 불러오기</Button>
</div>
) : (
<div className="flex flex-1 flex-col items-center justify-center gap-2.5">
<p className="text-title-lg">
&apos;{q}&apos;와 맞는 종이 없어요
</p>
<p className="text-body text-fg-secondary">
철자를 확인하거나 새 종으로 추가해 주세요.
</p>
<Button onClick={() => setEditing({ draft: { name: q } })}>
+ {q} 종 추가
</Button>
</div>
)
}
/>
</main>
Expand Down
4 changes: 2 additions & 2 deletions src/features/species/queries.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { loadQuery } from "@/lib/loadError";
import { getSpecies, saveSpecies, setHidden } from "./api";
import type { Species } from "./components/SpeciesTable";

Expand All @@ -8,8 +9,7 @@ export const useSpecies = () =>
useQuery({
queryKey: speciesKey,
queryFn: getSpecies,
// 대시보드(useStats)처럼 실패하면 기다리지 않고 바로 실패로 둔다
retry: false,
...loadQuery,
});

// 서버가 저장한 종으로 목록 캐시를 바꾼다. 처음 보는 id면 새로 추가한 종이라 끝에 붙인다
Expand Down
51 changes: 51 additions & 0 deletions src/lib/loadError.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { afterEach, expect, test, vi } from "vitest";
import { setServer } from "@/test/fakeServer";
import { api } from "./api";
import { commonError, loadQuery } from "./loadError";

afterEach(() => vi.restoreAllMocks());

const failure = (status: number) => {
setServer(() => [status, {}]);
return api.get("/admin/stats").catch((e: unknown) => e);
};

test("5xx는 상태 코드, 4xx와 그 밖의 에러는 화면별 실패 화면", async () => {
expect(commonError(await failure(500))).toBe(500);
expect(commonError(await failure(503))).toBe(503);
expect(commonError(await failure(404))).toBeUndefined();
expect(commonError(new Error("render"))).toBeUndefined();
});

test("응답이 없으면 브라우저가 오프라인일 때만 연결 끊김", async () => {
const { AxiosError } = await import("axios");
const noResponse = new AxiosError("Network Error");
expect(commonError(noResponse)).toBeUndefined();
vi.spyOn(navigator, "onLine", "get").mockReturnValue(false);
expect(commonError(noResponse)).toBe("offline");
});

test("받은 값이 있으면 갱신이 실패해도 공통 오류 화면으로 보내지 않는다", async () => {
const error = await failure(500);
expect(loadQuery.throwOnError(error, { state: { data: undefined } })).toBe(
true,
);
expect(loadQuery.throwOnError(error, { state: { data: {} } })).toBe(false);
});

test("오프라인이어도 요청을 미루지 않고 실패한다", async () => {
const { onlineManager } = await import("@tanstack/react-query");
onlineManager.setOnline(false);
const observer = new QueryObserver(new QueryClient(), {
...loadQuery,
queryKey: ["x"],
queryFn: () => Promise.reject(new Error("offline")),
});
const unsubscribe = observer.subscribe(() => {});
await vi.waitFor(() =>
expect(observer.getCurrentResult().isError).toBe(true),
);
unsubscribe();
onlineManager.setOnline(true);
});
21 changes: 21 additions & 0 deletions src/lib/loadError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { isAxiosError } from "axios";

// 공통 오류 화면(app/error.tsx)의 종류. "offline"은 W-E4, 숫자(5xx 상태 코드)는 W-E3.
// undefined면 화면마다 있는 실패 화면(W-2a · W-3j · W-4g)이 맡는다
export function commonError(error: unknown) {
if (!isAxiosError(error)) return;
const status = error.response?.status;
if (status === undefined) return navigator.onLine ? undefined : "offline";
return status >= 500 ? status : undefined;
}

// 화면을 처음 불러오는 쿼리의 공통 설정
export const loadQuery = {
// 실패하면 기다리지 않고 바로 오류 화면을 띄운다. 다시 시도는 화면의 버튼으로 한다
retry: false,
// 기본값은 오프라인이면 요청을 미뤄 빈 화면에 멈추므로, 바로 보내서 실패하게 한다
networkMode: "always",
// 이미 받은 값이 있으면 자동 갱신이 실패해도 화면을 바꾸지 않는다
throwOnError: (error: unknown, query: { state: { data: unknown } }) =>
query.state.data === undefined && commonError(error) !== undefined,
} as const;