diff --git a/src/_storybook/views/grammar-detail/GrammarHistory.stories.tsx b/src/_storybook/views/grammar-detail/GrammarHistory.stories.tsx new file mode 100644 index 0000000..dc18a00 --- /dev/null +++ b/src/_storybook/views/grammar-detail/GrammarHistory.stories.tsx @@ -0,0 +1,27 @@ +import type { Meta, StoryObj } from "@storybook/nextjs-vite"; +import { GrammarHistory } from "@/features/grammar-history"; +import type { GrammarHistoryProps } from "@/features/grammar-history"; + +const data = { + items: [], + total: 0, + page: 1, + pageSize: 10, +}; +const load: GrammarHistoryProps["load"] = async () => ({ ok: true, data }); + +const meta = { + title: "views/grammar/History", + component: GrammarHistory, + args: { noteId: "preview-note", load }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Cached: Story = { args: { initialData: data } }; +export const Loading: Story = { + args: { + load: () => new Promise((resolve) => setTimeout(() => resolve({ ok: true, data }), 4000)), + }, +}; diff --git a/src/_tests/features/grammar-history/GrammarHistory.test.tsx b/src/_tests/features/grammar-history/GrammarHistory.test.tsx index ec0434e..3bdcb16 100644 --- a/src/_tests/features/grammar-history/GrammarHistory.test.tsx +++ b/src/_tests/features/grammar-history/GrammarHistory.test.tsx @@ -44,7 +44,50 @@ describe("grammar history", () => { expect(load).toHaveBeenCalledTimes(2); }); - it("refreshes the latest date and keeps it while paging older records", async () => { + it("reopens cached history without another request and accepts a newly completed record", async () => { + const user = userEvent.setup(); + const data = { items: [], total: 0, page: 1, pageSize: 10 }; + const load = jest + .fn<() => Promise>() + .mockResolvedValue({ ok: true, data }); + const { rerender } = render(); + const trigger = screen.getByRole("button", { name: "연습 기록 전체보기" }); + + await user.click(trigger); + expect(await screen.findByText("아직 완료한 연습이 없습니다.")).toBeVisible(); + await user.keyboard("{Escape}"); + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); + await user.click(trigger); + expect(screen.getByText("아직 완료한 연습이 없습니다.")).toBeVisible(); + expect(load).not.toHaveBeenCalled(); + + const completedAt = "2026-10-18T01:00:00Z"; + rerender( + , + ); + expect(screen.getByText("완료한 연습 1회")).toBeVisible(); + expect(load).not.toHaveBeenCalled(); + }); + + it("keeps the latest completed date while paging older records", async () => { const user = userEvent.setup(); const oldDate = "2026-10-01T00:00:00Z"; const latestDate = "2026-10-03T00:00:00Z"; @@ -57,13 +100,14 @@ describe("grammar history", () => { completedAt: oldDate, questionCount: 1, }; - const initialData = { items: [item], total: 1, page: 1, pageSize: 10 }; + const initialData = { + items: [{ ...item, completedAt: latestDate }], + total: 21, + page: 1, + pageSize: 10, + }; const load = jest .fn<() => Promise>() - .mockResolvedValueOnce({ - ok: true, - data: { ...initialData, total: 21, items: [{ ...item, completedAt: latestDate }] }, - }) .mockResolvedValueOnce({ ok: true, data: { ...initialData, total: 21, page: 2 } }); render( diff --git a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts index 9831c45..fa75c29 100644 --- a/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts +++ b/src/_tests/features/grammar-note-editor/saveGrammarNote.test.ts @@ -22,6 +22,7 @@ jest.mock("server-only", () => ({})); jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); +jest.mock("next/cache", () => ({ revalidatePath: jest.fn() })); Object.defineProperty(globalThis.crypto, "randomUUID", { value: randomUUID, configurable: true }); @@ -74,12 +75,13 @@ describe("어법 저장 서버 경계", () => { it("정상 저장은 동일 요청 ID와 검토 내용을 저장소에 전달한다", async () => { const input = command(); - const create = jest - .spyOn(GrammarNoteRepository.prototype, "create") - .mockResolvedValue(createEditorNote()); + const note = createEditorNote(); + const create = jest.spyOn(GrammarNoteRepository.prototype, "create").mockResolvedValue(note); expect((await saveGrammarNote(input)).ok).toBe(true); expect(create).toHaveBeenCalledWith(input); + const { revalidatePath } = await import("next/cache"); + expect(revalidatePath).toHaveBeenCalledWith(`/grammar/${note.id}`); }); it("수정 저장 응답을 잃은 재시도는 이미 저장한 동일 버전을 성공으로 돌려준다", async () => { @@ -98,6 +100,8 @@ describe("어법 저장 서버 경계", () => { expect(result.ok).toBe(true); expect(update).toHaveBeenCalledTimes(1); + const { revalidatePath } = await import("next/cache"); + expect(revalidatePath).toHaveBeenCalledWith(`/grammar/${note.id}`); }); it("내용이 다른 버전 충돌을 성공으로 오인하지 않고 초안 재검토를 요청한다", async () => { @@ -120,6 +124,8 @@ describe("어법 저장 서버 경계", () => { ok: false, code: "VERSION_CONFLICT", }); + const { revalidatePath } = await import("next/cache"); + expect(revalidatePath).not.toHaveBeenCalled(); }); it("실패는 내부 이벤트로 기록하고 원문과 내부 오류를 UI에 노출하지 않는다", async () => { diff --git a/src/_tests/features/grammar-practice/grammarSessionActions.test.ts b/src/_tests/features/grammar-practice/grammarSessionActions.test.ts index 02b856a..497d815 100644 --- a/src/_tests/features/grammar-practice/grammarSessionActions.test.ts +++ b/src/_tests/features/grammar-practice/grammarSessionActions.test.ts @@ -9,7 +9,7 @@ jest.mock("server-only", () => ({})); jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() })); -jest.mock("next/cache", () => ({ revalidateTag: jest.fn() })); +jest.mock("next/cache", () => ({ revalidateTag: jest.fn(), revalidatePath: jest.fn() })); let createSupabaseServerClient: typeof CreateClient; @@ -52,7 +52,7 @@ describe("어법 연습 완료 후 통계 캐시", () => { } as never); const complete = jest .spyOn(GrammarSessionRepository.prototype, "complete") - .mockResolvedValue({} as never); + .mockResolvedValue({ noteId: "note-id" } as never); expect( ( @@ -63,6 +63,8 @@ describe("어법 연습 완료 후 통계 캐시", () => { ).ok, ).toBe(true); expect(revalidateTag).toHaveBeenCalledWith("my-page-practice-stats:owner", { expire: 0 }); + const { revalidatePath } = await import("next/cache"); + expect(revalidatePath).toHaveBeenCalledWith("/grammar/note-id"); complete.mockRestore(); }); @@ -86,6 +88,8 @@ describe("어법 연습 완료 후 통계 캐시", () => { ).ok, ).toBe(false); expect(revalidateTag).not.toHaveBeenCalled(); + const { revalidatePath } = await import("next/cache"); + expect(revalidatePath).not.toHaveBeenCalled(); complete.mockRestore(); }); }); diff --git a/src/_tests/views/grammar/grammarRoutes.test.tsx b/src/_tests/views/grammar/grammarRoutes.test.tsx index 9431a7e..569d0f7 100644 --- a/src/_tests/views/grammar/grammarRoutes.test.tsx +++ b/src/_tests/views/grammar/grammarRoutes.test.tsx @@ -1,12 +1,33 @@ /** @jest-environment node */ import { beforeEach, describe, expect, it, jest } from "@jest/globals"; import { recallSession } from "@/_tests/features/grammar-recall/fixture"; +import { createEditorNote } from "@/_tests/features/grammar-note-editor/fixtures"; import { grammarReturnTo } from "@/views/grammar-detail/services/grammarReturnTo"; +jest.mock("server-only", () => ({})); +jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() })); +jest.mock("@supabase/supabase-js", () => ({ createClient: jest.fn(() => ({})) })); +jest.mock("next/cache", () => { + const entries = new Map>(); + return { + unstable_cache: jest.fn((read: (...args: unknown[]) => Promise, keys: string[]) => { + return (...args: unknown[]) => { + const key = JSON.stringify([keys, args]); + if (!entries.has(key)) entries.set(key, read(...args)); + return entries.get(key); + }; + }), + __clearTestCache: () => entries.clear(), + }; +}); + jest.mock("next/navigation", () => ({ redirect: (url: string) => { throw new Error(`redirect:${url}`); }, + notFound: () => { + throw new Error("not-found"); + }, })); jest.mock("@/views/grammar-session/services/loadGrammarSession", () => ({ @@ -106,3 +127,70 @@ describe("grammar route transitions", () => { expect(grammarReturnTo("/grammar?q=contrast&page=2")).toBe("/grammar?q=contrast&page=2"); }); }); + +describe("private grammar detail", () => { + it("reuses one owner's note and history on revisit without exposing them to another owner", async () => { + const { createSupabaseServerClient } = await import("@/shared/lib/supabase/server"); + const { GrammarNoteRepository } = await import("@/entities/grammar-note"); + const { GrammarSessionRepository } = await import("@/entities/grammar-session"); + const { __clearTestCache } = jest.requireMock<{ __clearTestCache: () => void }>("next/cache"); + __clearTestCache(); + + let owner: string | null = "owner-a"; + jest.mocked(createSupabaseServerClient).mockImplementation( + async () => + ({ + auth: { + getUser: async () => ({ data: { user: owner ? { id: owner } : null }, error: null }), + getSession: async () => ({ + data: { + session: owner ? { user: { id: owner }, access_token: `${owner}-token` } : null, + }, + error: null, + }), + }, + }) as never, + ); + process.env.NEXT_PUBLIC_SUPABASE_URL = "https://example.supabase.co"; + process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY = "publishable-key"; + + const note = { ...createEditorNote(), ownerId: "owner-a" }; + const noteRead = jest + .spyOn(GrammarNoteRepository.prototype, "findById") + .mockImplementation(async (id) => (owner === "owner-a" && id === note.id ? note : null)); + const historyRead = jest + .spyOn(GrammarSessionRepository.prototype, "findHistory") + .mockResolvedValue({ + items: [], + total: 0, + page: 1, + pageSize: 10, + }); + const { default: Page } = await import("@/app/(protected)/grammar/[id]/page"); + const props = { + params: Promise.resolve({ id: note.id }), + searchParams: Promise.resolve({ returnTo: "/grammar?page=2" }), + }; + + try { + const first = await Page(props); + const revisit = await Page(props); + expect(first.props.note).toMatchObject({ id: note.id, ownerId: "owner-a" }); + expect(revisit.props.backHref).toBe("/grammar?page=2"); + expect(noteRead).toHaveBeenCalledTimes(1); + expect(historyRead).toHaveBeenCalledTimes(1); + + await expect( + Page({ ...props, params: Promise.resolve({ id: "00000000-0000-4000-8000-000000000002" }) }), + ).rejects.toThrow("not-found"); + owner = "owner-b"; + await expect(Page(props)).rejects.toThrow("not-found"); + owner = null; + await expect(Page(props)).rejects.toThrow("not-found"); + } finally { + noteRead.mockRestore(); + historyRead.mockRestore(); + jest.mocked(createSupabaseServerClient).mockReset(); + } + }); +}); diff --git a/src/app/(protected)/grammar/[id]/page.tsx b/src/app/(protected)/grammar/[id]/page.tsx index c9f9e8c..748b800 100644 --- a/src/app/(protected)/grammar/[id]/page.tsx +++ b/src/app/(protected)/grammar/[id]/page.tsx @@ -1,5 +1,6 @@ -import { GrammarDetailView, loadGrammarNote, grammarReturnTo } from "@/views/grammar-detail"; -import { getGrammarHistory } from "@/features/grammar-history/services/actions/getGrammarHistory"; +import { GrammarDetailView, grammarReturnTo } from "@/views/grammar-detail"; +import { loadCachedGrammarDetailNote } from "@/views/grammar-detail/services/loadGrammarNote"; +import { getCachedGrammarDetailHistory } from "@/features/grammar-history/services/actions/getGrammarHistory"; export default async function GrammarNotePage({ params, @@ -9,8 +10,8 @@ export default async function GrammarNotePage({ searchParams: Promise<{ returnTo?: string | string[] }>; }) { const [{ id }, query] = await Promise.all([params, searchParams]); - const note = await loadGrammarNote(id); - const history = await getGrammarHistory(id, 1); + const note = await loadCachedGrammarDetailNote(id); + const history = await getCachedGrammarDetailHistory(id); return ( { @@ -35,3 +37,30 @@ export async function getGrammarHistory(noteId: string, page = 1): Promise { + try { + const id = z.string().uuid().parse(noteId); + const access = await getPrivateGrammarCacheClient(); + if (!access) throw new GrammarSessionError("UNAUTHORIZED"); + + const read = unstable_cache( + () => + new GrammarSessionRepository(access.client).findHistory({ + noteId: id, + page: 1, + pageSize: 10, + }), + ["grammar-detail-history", access.ownerId, id], + { revalidate: 60 }, + ); + return await observeOperation({ + operation: "grammar.history", + resourceId: "grammar-note", + recordEvent: recordOperationEvent, + execute: async () => ({ ok: true as const, data: await read() }), + }); + } catch { + return { ok: false, code: "LOAD_FAILED" }; + } +} diff --git a/src/features/grammar-history/services/useGrammarHistory.ts b/src/features/grammar-history/services/useGrammarHistory.ts index 068a98c..0b7e40a 100644 --- a/src/features/grammar-history/services/useGrammarHistory.ts +++ b/src/features/grammar-history/services/useGrammarHistory.ts @@ -20,6 +20,14 @@ export function useGrammarHistory({ noteId, initialData, load }: GrammarHistoryP }; }, []); + useEffect(() => { + generation.current++; + setData(initialData); + setLatestCompletedAt(initialData?.page === 1 ? initialData.items[0]?.completedAt : undefined); + setBusy(false); + setError(null); + }, [initialData]); + async function refresh(page = 1) { const currentGeneration = ++generation.current; diff --git a/src/features/grammar-history/ui/GrammarHistory.tsx b/src/features/grammar-history/ui/GrammarHistory.tsx index 3ff14b6..5cf6b35 100644 --- a/src/features/grammar-history/ui/GrammarHistory.tsx +++ b/src/features/grammar-history/ui/GrammarHistory.tsx @@ -29,7 +29,7 @@ function HistoryForNote(props: GrammarHistoryProps) { function changeOpen(next: boolean) { setOpen(next); - if (next) void refresh(1); + if (next && (!data || error)) void refresh(1); } return ( @@ -37,7 +37,7 @@ function HistoryForNote(props: GrammarHistoryProps) {

나의 연습

{data ? `완료한 연습 ${total}회` : "완료한 연습 기록을 확인해보세요."} - {last && ` · 최근 ${formatGrammarPracticeDate(last)}`} + {last && ` · 최근 ${formatGrammarPracticeDate(last)}`}

diff --git a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts index fd9b67d..7b90f4b 100644 --- a/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts +++ b/src/features/grammar-note-editor/services/actions/saveGrammarNote.ts @@ -4,6 +4,7 @@ import { GrammarNotePersistenceError, GrammarNoteRepository } from "@/entities/g import { createSupabaseServerClient } from "@/shared/lib/supabase/server"; import { observeOperation } from "@/shared/lib/logging/observeOperation"; import { recordOperationEvent } from "@/shared/lib/logging/pino"; +import { invalidateGrammarDetail } from "@/shared/lib/query/grammarDetailCache"; import { persistReviewedNote } from "../persistReviewedNote"; import type { SaveNoteCommand, SaveNoteResult } from "../../models/interface"; @@ -26,6 +27,7 @@ export async function saveGrammarNote(command: SaveNoteCommand): Promise { const session = await repository.complete(completeGrammarSessionSchema.parse(input)); invalidatePracticeStats(ownerId); + invalidateGrammarDetail(session.noteId); return session; }); } diff --git a/src/shared/lib/query/grammarDetailCache.ts b/src/shared/lib/query/grammarDetailCache.ts new file mode 100644 index 0000000..7b02bb1 --- /dev/null +++ b/src/shared/lib/query/grammarDetailCache.ts @@ -0,0 +1,40 @@ +import "server-only"; + +import { createClient } from "@supabase/supabase-js"; +import { revalidatePath } from "next/cache"; +import { createSupabaseServerClient } from "@/shared/lib/supabase/server"; +import type { Database } from "@/shared/lib/supabase/database.types"; + +export async function getPrivateGrammarCacheClient() { + const supabase = await createSupabaseServerClient(); + const [{ data, error }, sessionResult] = await Promise.all([ + supabase.auth.getUser(), + supabase.auth.getSession(), + ]); + const ownerId = data.user?.id; + const session = sessionResult.data.session; + + if (error || sessionResult.error || !ownerId || !session || session.user.id !== ownerId) { + return null; + } + + const url = process.env.NEXT_PUBLIC_SUPABASE_URL; + const key = process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY; + if (!url || !key) throw new Error("Supabase configuration is missing"); + + return { + ownerId, + client: createClient(url, key, { + auth: { persistSession: false, autoRefreshToken: false }, + global: { headers: { Authorization: `Bearer ${session.access_token}` } }, + }), + }; +} + +export function invalidateGrammarDetail(noteId: string) { + try { + revalidatePath(`/grammar/${noteId}`); + } catch (error) { + console.error("어법 상세 캐시 무효화 실패", error); + } +} diff --git a/src/views/grammar-detail/services/loadGrammarNote.ts b/src/views/grammar-detail/services/loadGrammarNote.ts index cb41cba..abc734a 100644 --- a/src/views/grammar-detail/services/loadGrammarNote.ts +++ b/src/views/grammar-detail/services/loadGrammarNote.ts @@ -1,10 +1,12 @@ import "server-only"; import { notFound } from "next/navigation"; +import { unstable_cache } from "next/cache"; import { z } from "zod"; import { GrammarNoteRepository } from "@/entities/grammar-note"; import { createSupabaseServerClient } from "@/shared/lib/supabase/server"; import { observeOperation } from "@/shared/lib/logging/observeOperation"; import { recordOperationEvent } from "@/shared/lib/logging/pino"; +import { getPrivateGrammarCacheClient } from "@/shared/lib/query/grammarDetailCache"; export async function loadGrammarNote(id: string) { if (!z.string().uuid().safeParse(id).success) notFound(); @@ -25,3 +27,23 @@ export async function loadGrammarNote(id: string) { return note; } + +export async function loadCachedGrammarDetailNote(id: string) { + if (!z.string().uuid().safeParse(id).success) notFound(); + const access = await getPrivateGrammarCacheClient(); + if (!access) notFound(); + + const read = unstable_cache( + () => new GrammarNoteRepository(access.client).findById(id), + ["grammar-detail-note", access.ownerId, id], + { revalidate: 60 }, + ); + const note = await observeOperation({ + operation: "grammar.note.read", + resourceId: id, + recordEvent: recordOperationEvent, + execute: read, + }); + if (!note) notFound(); + return note; +}