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
26 changes: 26 additions & 0 deletions src/_tests/shared/lib/supabase/getAuthenticatedUser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ jest.mock("next/navigation", () => ({
notFound: () => {
throw new Error("NEXT_NOT_FOUND");
},
redirect: (url: string) => {
throw new Error(`NEXT_REDIRECT:${url}`);
},
}));

describe("공용 사용자 인증 확인", () => {
Expand All @@ -28,4 +31,27 @@ describe("공용 사용자 인증 확인", () => {
} as never),
).rejects.toThrow("NEXT_NOT_FOUND");
});

it.each([
{ user: null, error: null },
{ user: { id: "owner" }, error: { message: "invalid token" } },
])("새 로그인 가드는 인증 실패 시 /login으로 이동한다: $error", async ({ user, error }) => {
const { requireUserOrRedirect } = await import("@/features/login/server");
const getUser = jest.fn(async () => ({ data: { user }, error }));

await expect(requireUserOrRedirect({ auth: { getUser } } as never)).rejects.toThrow(
"NEXT_REDIRECT:/login",
);
expect(getUser).toHaveBeenCalledTimes(1);
});

it("새 로그인 가드는 인증된 사용자의 ID를 반환한다", async () => {
const { requireUserOrRedirect } = await import("@/features/login/server");
const getUser = jest.fn(async () => ({ data: { user: { id: "owner" } }, error: null }));

await expect(requireUserOrRedirect({ auth: { getUser } } as never)).resolves.toEqual({
id: "owner",
});
expect(getUser).toHaveBeenCalledTimes(1);
});
});
101 changes: 98 additions & 3 deletions src/_tests/views/grammar-library/GrammarLibraryPage.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
/** @jest-environment node */
import { describe, it, expect, jest, beforeEach } from "@jest/globals";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";

import type { GrammarNoteRepository } from "@/entities/grammar-note";

jest.mock("server-only", () => ({}));
jest.mock("@/shared/lib/supabase/server", () => ({ createSupabaseServerClient: jest.fn() }));

jest.mock("@/shared/lib/logging/pino", () => ({ recordOperationEvent: jest.fn() }));
Expand All @@ -21,20 +24,112 @@ describe("grammar list route", () => {
const { createSupabaseServerClient } = await import("@/shared/lib/supabase/server");

jest.spyOn(GrammarNoteRepository.prototype, "findMany").mockImplementation(findMany);
findMany.mockClear();
jest.mocked(createSupabaseServerClient).mockResolvedValue({
auth: { getUser: async () => ({ data: { user: { id: "owner" } }, error: null }) },
} as unknown as Awaited<ReturnType<typeof createSupabaseServerClient>>);
findMany.mockResolvedValue({ items: [], total: 41, page: 999, pageSize: 20 });
findMany.mockResolvedValue({ items: [], total: 41, page: 999, pageSize: 10 });
});

it("redirects an out-of-range page to last valid page with search preserved", async () => {
const { GrammarLibraryContent } =
await import("@/views/grammar-library/ui/GrammarLibraryContent");

await expect(GrammarLibraryContent({ query: { page: 999, query: "verb" } })).rejects.toThrow(
"redirect:/grammar?q=verb&page=3",
"redirect:/grammar?q=verb&page=5",
);
expect(findMany).toHaveBeenCalledWith({ page: 999, pageSize: 20, query: "verb" });
expect(findMany).toHaveBeenCalledWith({ page: 999, pageSize: 10, query: "verb" });
});

it("loads ten notes through the named server service", async () => {
const { getGrammarLibraryPage } =
await import("@/views/grammar-library/services/server/getGrammarLibraryPage");
const query = { page: 2, query: "verb" };
const notePage = { items: [], total: 11, page: 2, pageSize: 10 };
findMany.mockResolvedValueOnce(notePage);

await expect(getGrammarLibraryPage(query)).resolves.toEqual(notePage);
expect(findMany).toHaveBeenCalledWith({ ...query, pageSize: 10 });
});

it("returns a list error only when the authenticated lookup fails", async () => {
const { getGrammarLibraryPage } =
await import("@/views/grammar-library/services/server/getGrammarLibraryPage");
findMany.mockRejectedValueOnce(new Error("database unavailable"));

await expect(getGrammarLibraryPage({ page: 1, query: "verb" })).resolves.toBeNull();
});

it("keeps the retry UI inside the list when the lookup fails", async () => {
const { GrammarLibraryContent } =
await import("@/views/grammar-library/ui/GrammarLibraryContent");
findMany.mockRejectedValueOnce(new Error("database unavailable"));

const html = renderToStaticMarkup(
await GrammarLibraryContent({ query: { page: 1, query: "verb" } }),
);
expect(html).toContain("어법 노트를 불러오지 못했습니다");
expect(html).toContain('href="/grammar?q=verb"');
});

it("redirects an unauthenticated list visit before querying notes", async () => {
const { createSupabaseServerClient } = await import("@/shared/lib/supabase/server");
jest.mocked(createSupabaseServerClient).mockResolvedValueOnce({
auth: { getUser: async () => ({ data: { user: null }, error: null }) },
} as unknown as Awaited<ReturnType<typeof createSupabaseServerClient>>);
const { GrammarLibraryContent } =
await import("@/views/grammar-library/ui/GrammarLibraryContent");

await expect(GrammarLibraryContent({ query: { page: 1, query: "" } })).rejects.toThrow(
"redirect:/login",
);
expect(findMany).not.toHaveBeenCalled();
});

it("renders the title and search before the note list resolves", async () => {
const { default: GrammarLibraryPage } = await import("@/app/(protected)/grammar/(list)/page");
const html = renderToStaticMarkup(
await GrammarLibraryPage({ searchParams: Promise.resolve({ q: "verb" }) }),
);

expect(html).toContain("어법 노트");
expect(html).toContain('name="q"');
expect(html).toContain('value="verb"');
expect(html).toContain("어법 노트를 불러오는 중");
expect(html).not.toContain("0개의 어법 노트");
});

it("keeps filtered page links and makes each note card the navigation target", async () => {
const { GrammarNoteList } = await import("@/views/grammar-library/ui/GrammarNoteList");
const html = renderToStaticMarkup(
createElement(GrammarNoteList, {
data: {
items: [
{
id: "11111111-1111-4111-8111-111111111111",
ownerId: "22222222-2222-4222-8222-222222222222",
version: 1,
createdAt: "2026-10-12T00:00:00Z",
updatedAt: "2026-10-12T00:00:00Z",
title: "Verb phrase",
sentence: "I have been reading.",
tags: ["verb"],
},
],
total: 11,
page: 1,
pageSize: 10,
},
query: "verb",
}),
);

expect(html).toContain(
'href="/grammar/11111111-1111-4111-8111-111111111111?returnTo=%2Fgrammar%3Fq%3Dverb"',
);
expect(html).toContain('href="/grammar?q=verb&amp;page=2"');
expect(html).not.toContain(">→</span>");
expect(html).toContain("active:scale");
});

it("normalizes an invalid URL before rendering valid links", async () => {
Expand Down
6 changes: 6 additions & 0 deletions src/_tests/views/grammar-library/libraryQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,10 @@ describe("grammar library URL", () => {
page: 2,
query: "verb",
}));

it("keeps the search term in page links and starts a new search on page one", () => {
const query = parseGrammarLibraryQuery({ q: " verb phrase ", page: "2" });
expect(grammarLibraryHref(query)).toBe("/grammar?q=verb+phrase&page=2");
expect(grammarLibraryHref({ ...query, page: 1 })).toBe("/grammar?q=verb+phrase");
});
});
51 changes: 47 additions & 4 deletions src/app/(protected)/grammar/(list)/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Suspense } from "react";
import Link from "next/link";
import Form from "next/form";
import { redirect } from "next/navigation";
import {
GrammarLibrarySkeleton,
parseGrammarLibraryQuery,
grammarLibraryHref,
} from "@/views/grammar-library";
import { GrammarLibraryContent } from "@/views/grammar-library/ui/GrammarLibraryContent";
import { BackNavigation } from "@/shared/components/ui/back-navigation/BackNavigation";

interface Props {
searchParams: Promise<{ page?: string | string[]; q?: string | string[] }>;
Expand All @@ -21,10 +24,50 @@ export default async function GrammarLibraryPage({ searchParams }: Props) {
)
redirect(grammarLibraryHref(query));

// 검색어/페이지 변경도 새 데이터가 준비될 때까지 해당 목록의 스켈레톤을 보여준다.
return (
<Suspense key={grammarLibraryHref(query)} fallback={<GrammarLibrarySkeleton />}>
<GrammarLibraryContent query={query} />
</Suspense>
<div className="mx-auto max-w-5xl space-y-9 px-6 py-8">
<BackNavigation href="/home" />
<header className="flex flex-wrap items-end justify-between gap-5">
<div>
<p className="mb-3 text-xs tracking-widest text-practice-secondary">GRAMMAR PRACTICE</p>
<h1 className="text-3xl font-medium text-practice-ink">어법 노트</h1>
<p className="mt-3 text-practice-secondary">배운 어법을 문장으로 기억하세요.</p>
</div>
<Link
href={`/grammar/new?returnTo=${encodeURIComponent(grammarLibraryHref(query))}`}
className="rounded-md bg-practice-accent px-5 py-3 text-sm text-white"
>
새 노트 작성 →
</Link>
</header>
<Form action="/grammar" className="flex gap-3">
<label htmlFor="grammar-search" className="sr-only">
어법 제목 또는 문장 검색
</label>
<input
key={query.query}
id="grammar-search"
name="q"
type="search"
maxLength={200}
defaultValue={query.query}
placeholder="어법 제목 또는 문장 검색"
className="min-w-0 flex-1 rounded-lg border border-practice-line bg-white px-4 py-3 text-practice-ink focus-visible:outline-practice-focus"
/>
<button type="submit" className="rounded-lg border border-practice-line px-5 text-sm">
검색
</button>
</Form>
<Suspense
key={grammarLibraryHref(query)}
fallback={
<div className="mx-auto max-w-4xl">
<GrammarLibrarySkeleton />
</div>
}
>
<GrammarLibraryContent query={query} />
</Suspense>
</div>
);
}
2 changes: 1 addition & 1 deletion src/features/login/server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import "server-only";

export { requireUser } from "./services/requireUser";
export { requireUser, requireUserOrRedirect } from "./services/requireUser";
12 changes: 11 additions & 1 deletion src/features/login/services/requireUser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getAuthenticatedUser } from "@/shared/lib/supabase/getAuthenticatedUser";
import { notFound } from "next/navigation";
import { notFound, redirect } from "next/navigation";

// shared
import type { createSupabaseServerClient } from "@/shared/lib/supabase/server";
Expand All @@ -18,3 +18,13 @@ export const requireUser = async (

return { id: user.id as UserId };
};

export const requireUserOrRedirect = async (
supabase: Awaited<ReturnType<typeof createSupabaseServerClient>>,
) => {
const user = await getAuthenticatedUser(supabase);

if (!user) redirect("/login");

return { id: user.id as UserId };
};
20 changes: 20 additions & 0 deletions src/views/grammar-library/services/server/getGrammarLibraryPage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import "server-only";

import { GrammarNoteRepository } from "@/entities/grammar-note";
import { requireUserOrRedirect } from "@/features/login/server";
import { observeOperation } from "@/shared/lib/logging/observeOperation";
import { recordOperationEvent } from "@/shared/lib/logging/pino";
import { createSupabaseServerClient } from "@/shared/lib/supabase/server";
import type { GrammarLibraryQuery } from "../../models/interface";

export async function getGrammarLibraryPage(query: GrammarLibraryQuery) {
const supabase = await createSupabaseServerClient();
await requireUserOrRedirect(supabase);

return observeOperation({
operation: "grammar.list",
resourceId: "grammar-library",
recordEvent: recordOperationEvent,
execute: () => new GrammarNoteRepository(supabase).findMany({ ...query, pageSize: 10 }),
}).catch(() => null);
}
38 changes: 17 additions & 21 deletions src/views/grammar-library/ui/GrammarLibraryContent.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
import { redirect } from "next/navigation";
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 type { GrammarLibraryQuery } from "../models/interface";
import { grammarLibraryHref } from "../services/libraryQuery";
import { GrammarLibraryView } from "./GrammarLibraryView";
import { getGrammarLibraryPage } from "../services/server/getGrammarLibraryPage";
import { GrammarNoteList } from "./GrammarNoteList";

export async function GrammarLibraryContent({ query }: { query: GrammarLibraryQuery }) {
Comment thread
Yelihi marked this conversation as resolved.
Resolved
const supabase = await createSupabaseServerClient();
const {
data: { user },
error,
} = await supabase.auth.getUser();
const notePage = await getGrammarLibraryPage(query);

if (error || !user) redirect("/login");

const data = await observeOperation({
operation: "grammar.list",
resourceId: "grammar-library",
recordEvent: recordOperationEvent,

execute: () => new GrammarNoteRepository(supabase).findMany({ ...query, pageSize: 20 }),
});
const page = Math.min(query.page, Math.max(1, Math.ceil(data.total / data.pageSize)));
if (!notePage) {
return (
<section aria-label="어법 노트 목록" className="mx-auto max-w-4xl space-y-4">
<p role="alert" className="text-practice-secondary">
어법 노트를 불러오지 못했습니다. 잠시 후 다시 시도해주세요.
</p>
<a href={grammarLibraryHref(query)} className="text-practice-accent underline">
다시 불러오기
</a>
</section>
);
}
const page = Math.min(query.page, Math.max(1, Math.ceil(notePage.total / notePage.pageSize)));

if (page !== query.page) redirect(grammarLibraryHref({ ...query, page }));

return <GrammarLibraryView data={data} query={query.query} />;
return <GrammarNoteList data={notePage} query={query.query} />;
}
14 changes: 3 additions & 11 deletions src/views/grammar-library/ui/GrammarNoteList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function GrammarNoteList({ data, query }: GrammarNoteListProps) {
const pages = Math.max(1, Math.ceil(data.total / data.pageSize));

return (
<section aria-label="어법 노트 목록" className="space-y-8">
<section aria-label="어법 노트 목록" className="mx-auto w-full max-w-4xl space-y-8">
<p className="text-sm text-practice-secondary">{data.total}개의 어법 노트</p>
{data.items.length === 0 ? (
<div className="rounded-xl border border-practice-line bg-white p-12 text-center">
Expand All @@ -27,17 +27,9 @@ export function GrammarNoteList({ data, query }: GrammarNoteListProps) {
<li key={note.id}>
<Link
href={`/grammar/${note.id}?returnTo=${encodeURIComponent(returnTo)}`}
className="group block py-7 transition-colors hover:bg-white focus-visible:outline-2 focus-visible:outline-practice-focus"
className="block px-5 py-7 transition-[background-color,transform,box-shadow] duration-200 hover:bg-white hover:shadow-sm active:scale-[0.99] focus-visible:outline-2 focus-visible:outline-practice-focus motion-reduce:transition-none motion-reduce:transform-none sm:px-8"
>
<div className="flex items-center justify-between gap-4">
<h2 className="text-xl font-medium text-practice-ink">{note.title}</h2>
<span
aria-hidden
className="text-practice-secondary transition-transform group-hover:translate-x-1 motion-reduce:transform-none"
>
→
</span>
</div>
<h2 className="text-xl font-medium text-practice-ink">{note.title}</h2>
<p className="mt-2 text-base text-practice-body">{note.sentence}</p>
<div className="mt-4 flex flex-wrap gap-2">
{note.tags.map((tag) => (
Expand Down
Loading