본문으로 건너뛰기

통계 쪽

Next.js 목차 레시피 보관함 Next.js 판 레슨 44 / 47

목차

통계 쪽은 /stats에서 레시피의 전체 수 · 평균 분 · 즐겨찾기 수 · 분류별 수를 보이는 쪽입니다. 이 레슨은 그 셈을 서버 컴포넌트에서 하고, 맨 아래에 백업 내려받기 링크를 달아 레시피 보관함 Next.js 판을 마칩니다.

리액트 판 StatsScreen은 브라우저에서 목록을 받아 렌더할 때마다 셌습니다(레시피 보관함 — 고치기 · 정렬 · 통계 · 백업 3절). 셈하는 코드와 목록 전체가 브라우저로 가야 했습니다. Next.js 판은 서버에서 다 세고, 브라우저에는 다 센 HTML만 보냅니다.

1셈은 서버에서

지금 통계 쪽은 Promise 넘기기와 use에서 지은 꼴입니다. 쪽이 getRecipes()의 Promise를 클라이언트 컴포넌트 Count에 넘기고, Count가 use로 열어 수 하나를 셉니다. 셈이 넷으로 늘면 넷 다 서버에서 하는 편이 낫습니다. 쪽 함수를 async로 바꿔 직접 기다리고, 셈한 수만 그립니다.

app/stats/page.tsx
…
async function Page() {
  // 1. 기억한 목록 읽기
  const recipes =
    await getRecipes();
  // 2. 서버에서 셈하기
  const total = recipes.length;
  …
  const countOf = (c: string) =>
    recipes.filter(
      (r) => r.category === c,
    ).length;
  …
  • 1. getRecipes는 'use cache' 함수라 한 시간 기억한 목록을 줍니다. 쪽이 직접 기다려도 그 결과는 기억한 목록입니다. 경로 표가 이 쪽을 어떻게 적는지는 예제에서 봅니다.
  • 2. 전체 · 평균 · 즐겨찾기는 리액트 판 StatsScreen의 셈 그대로입니다. 분류별 수 countOf는 categories 다섯마다 그 분류의 레시피를 세어, 한식 2개 꼴의 <li> 줄로 그립니다.
  • 3. 맨 아래 '백업 내려받기'는 단원 8의 경로 처리기 /api/recipes로 가는 링크입니다(해 보기). Link는 쪽 사이를 옮겨 다니는 링크라, 쪽이 아닌 경로 처리기 주소에는 <a>를 씁니다.

쪽에 클라이언트 컴포넌트가 없어졌으니 Suspense · Count import를 지우고, components/Count.tsx 파일도 지웁니다.

app/stats/page.tsx 전체
app/stats/page.tsx
import type {
  Metadata,
} from 'next';
import {
  categories,
  getRecipes,
} from '@/lib/recipes';
import styles from
  './page.module.css';

export const
  metadata: Metadata = {
    title: '통계',
  };

async function Page() {
  // 1. 기억한 목록 읽기
  const recipes =
    await getRecipes();
  // 2. 서버에서 셈하기
  const total = recipes.length;
  const sum = recipes.reduce(
    (s, r) => s + r.minutes,
    0,
  );
  const average =
    total === 0
      ? 0
      : Math.round(sum / total);
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  const countOf = (c: string) =>
    recipes.filter(
      (r) => r.category === c,
    ).length;
  const rows = categories.map(
    (c) => (
      <li key={c}>
        {c} {countOf(c)}개
      </li>
    ),
  );
  return (
    <>
      <h1
        className={styles.card}
      >
        통계
      </h1>
      <p>전체 {total}개</p>
      <p>평균 {average}분</p>
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <ul>{rows}</ul>
      {/* 3. 내보내기 링크 */}
      <a href="/api/recipes">
        백업 내려받기
      </a>
    </>
  );
}

export default Page;

2별을 바꾸면 통계도

통계 쪽을 연 뒤 목록에서 토마토 파스타의 ☆를 누르고, 메뉴의 '통계'를 누릅니다. 즐겨찾기는 몇 개로 보일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 2개 — 통계 쪽은 한 시간 기억한 목록으로 센다
  • ② 3개 — 별을 저장할 때 같은 'recipes' 기억을 지웠다
  • ③ 새로 고쳐야 3개
결과 보기

②입니다. 아래는 1절 그대로의 통계 쪽 파일, 처음 연 통계 쪽, 별을 누르고 다시 연 통계 쪽입니다.

app/stats/page.tsx
import type {
  Metadata,
} from 'next';
import {
  categories,
  getRecipes,
} from '@/lib/recipes';
import styles from
  './page.module.css';

export const
  metadata: Metadata = {
    title: '통계',
  };

async function Page() {
  // 1. 기억한 목록 읽기
  const recipes =
    await getRecipes();
  // 2. 서버에서 셈하기
  const total = recipes.length;
  const sum = recipes.reduce(
    (s, r) => s + r.minutes,
    0,
  );
  const average =
    total === 0
      ? 0
      : Math.round(sum / total);
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  const countOf = (c: string) =>
    recipes.filter(
      (r) => r.category === c,
    ).length;
  const rows = categories.map(
    (c) => (
      <li key={c}>
        {c} {countOf(c)}개
      </li>
    ),
  );
  return (
    <>
      <h1
        className={styles.card}
      >
        통계
      </h1>
      <p>전체 {total}개</p>
      <p>평균 {average}분</p>
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <ul>{rows}</ul>
      {/* 3. 내보내기 링크 */}
      <a href="/api/recipes">
        백업 내려받기
      </a>
    </>
  );
}

export default Page;
<nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav>
<h1>통계</h1>
<p>전체 4개</p>
<p>평균 18분</p>
<p>즐겨찾기 2개</p>
<ul>
  <li>한식 2개</li>
  <li>양식 1개</li>
  <li>일식 0개</li>
  <li>중식 0개</li>
  <li>디저트 1개</li>
</ul><a href="/api/recipes">백업 내려받기</a>
<footer>바닥글<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"></footer>
결과 화면
<nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav>
<h1>통계</h1>
<p>전체 4개</p>
<p>평균 18분</p>
<p>즐겨찾기 3개</p>
<ul>
  <li>한식 2개</li>
  <li>양식 1개</li>
  <li>일식 0개</li>
  <li>중식 0개</li>
  <li>디저트 1개</li>
</ul><a href="/api/recipes">백업 내려받기</a>
<footer>바닥글<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"></footer>
결과 화면

toggleFavorite의 updateTag('recipes')가 지운 기억은 목록만의 것이 아닙니다. 통계 쪽의 getRecipes도 같은 이름표입니다. 별을 저장한 요청에서 서버가 목록을 새로 읽어 기억을 다시 채웠고(즐겨찾기 예제 터미널), 다음에 연 통계 쪽은 그 새 목록으로 셉니다. 평균과 분류별 수는 그대로이고 즐겨찾기만 3개가 됩니다. 별을 한 번 더 누르면 data/recipes.json의 favorite도 false로 되돌아갑니다.

다 봤으면 토마토 파스타의 별을 한 번 더 눌러 처음처럼 ☆로 되돌립니다.

해 보기 — 백업 내려받기

통계 쪽 맨 아래 '백업 내려받기'를 누르면 브라우저는 무엇을 할까요? 고른 뒤 펼쳐 보세요.

  • ① /api/recipes로 옮겨 가 JSON 글을 보인다
  • ② recipes.json 파일로 내려받는다
  • ③ 통계 쪽을 새로 그린다
결과 보기

②입니다. 아래는 단원 8에서 지은 경로 처리기 그대로와, 그 주소에 GET을 보낸 응답 머리입니다.

app/api/recipes/route.ts
import {
  readFile,
} from 'node:fs/promises';

// 받는 쪽이 파일로 저장하게
const headers = {
  'Content-Disposition':
    'attachment; filename=' +
    '"recipes.json"',
};

export async function GET() {
  const text = await readFile(
    'data/recipes.json',
    'utf8',
  );
  return Response.json(
    JSON.parse(text),
    { headers },
  );
}
실행 결과
HTTP/1.1 200 OK
content-disposition: attachment; filename="recipes.json"
content-type: application/json

content-disposition 머리의 attachment가 '탭에 그리지 말고 파일로 받으라'는 뜻입니다(경로 처리기). 받은 recipes.json을 편집기로 열면 줄바꿈 없이 한 줄입니다(Response.json은 들여쓰지 않습니다). 레시피 넷과 값은 지금 data/recipes.json과 같습니다.

예제

레시피 보관함 Next.js 판이 다 섰습니다. 개발 서버를 Ctrl+C로 끄고 npm run build를 돌립니다. 통계 쪽 함수는 이제 async이고 await로 목록을 기다립니다. 경로 표의 /stats 줄은 무엇일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① ƒ /stats — 기다리는 쪽은 요청 때 그린다
  • ② ◐ /stats — 기다리는 곳이 구멍이 된다
  • ③ ○ /stats · 1h · 1d — 기억한 결과로 미리 그린다
결과 보기

③입니다. 아래는 2절 그대로의 통계 쪽 파일과 빌드 출력입니다. 시간과 일꾼 수는 다를 수 있습니다.

app/stats/page.tsx
import type {
  Metadata,
} from 'next';
import {
  categories,
  getRecipes,
} from '@/lib/recipes';
import styles from
  './page.module.css';

export const
  metadata: Metadata = {
    title: '통계',
  };

async function Page() {
  // 1. 기억한 목록 읽기
  const recipes =
    await getRecipes();
  // 2. 서버에서 셈하기
  const total = recipes.length;
  const sum = recipes.reduce(
    (s, r) => s + r.minutes,
    0,
  );
  const average =
    total === 0
      ? 0
      : Math.round(sum / total);
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  const countOf = (c: string) =>
    recipes.filter(
      (r) => r.category === c,
    ).length;
  const rows = categories.map(
    (c) => (
      <li key={c}>
        {c} {countOf(c)}개
      </li>
    ),
  );
  return (
    <>
      <h1
        className={styles.card}
      >
        통계
      </h1>
      <p>전체 {total}개</p>
      <p>평균 {average}분</p>
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <ul>{rows}</ul>
      {/* 3. 내보내기 링크 */}
      <a href="/api/recipes">
        백업 내려받기
      </a>
    </>
  );
}

export default Page;
  Creating an optimized production build ...
✓ Compiled successfully in 2.1s
  Running TypeScript ...
  Finished TypeScript in 1013ms ...
  Collecting page data using 10 workers ...
레시피 파일 읽음
✓ Collecting page data using 10 workers in 240ms
  Generating static pages using 10 workers (0/13) ...
레시피 하나 읽음 r1
레시피 파일 읽음
레시피 하나 읽음 r2
레시피 하나 읽음 r3
  Generating static pages using 10 workers (3/13)
  Generating static pages using 10 workers (6/13)
레시피 하나 읽음 r4
  Generating static pages using 10 workers (9/13)
✓ Generating static pages using 10 workers (13/13) in 387ms
  Finalizing page optimization ...
✓ Finalizing page optimization in 12ms

Route (app)            Revalidate  Expire
┌ ○ /
├ ○ /_not-found
├ ƒ /api/recipes
├ ◐ /recipes
├   /recipes/[id]
│ ├ ◐ /recipes/[id]
│ ├ ○ /recipes/r1              1h      1d
│ ├ ○ /recipes/r2              1h      1d
│ └ ◐ [+2 more paths]
├ ○ /recipes/new
└ ○ /stats                     1h      1d


ƒ Proxy (Middleware)

○  (Static)             prerendered as static content
◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed content
ƒ  (Dynamic)            server-rendered on demand

쪽이 기다리는 것은 기억한 getRecipes의 결과라, 빌드가 미리 그려 두고 한 시간 기억합니다(1h · 1d). 표에는 이 단원에서 지은 주소 여섯 / · /api/recipes · /recipes · /recipes/[id] · /recipes/new · /stats가 다 섭니다.

다 봤으면 npm run dev로 개발 서버를 다시 띄웁니다.

자주 틀리는 곳

틀린 생각: 별을 바꾼 수가 바로 보이려면 통계는 브라우저에서 다시 세야 한다.

맞는 규칙: 별을 저장하는 서버 함수가 'recipes' 기억을 지우니, 다음에 연 통계 쪽이 서버에서 새로 셉니다(2절). 셈 코드와 목록을 브라우저로 보낼 까닭이 없습니다.

틀린 생각: data/recipes.json을 편집기에서 고치면 통계 쪽도 바로 바뀐다.

맞는 규칙: 통계 쪽은 기억한 목록으로 셉니다. 기억을 지우는 것은 서버 함수의 updateTag라, 파일만 고치면 통계 쪽은 기억한 옛 수를 보입니다. 내려받기 /api/recipes는 파일을 그때그때 읽는 경로 처리기라 바로 새 값을 줍니다.

확인 문제

문제 1. 이 레슨의 통계 쪽에서 즐겨찾기 수는 어디서 셀까요?

  • ① 브라우저의 Count
  • ② 브라우저와 서버 둘 다
  • ③ 서버의 Page
정답

③입니다. 쪽 함수 Page가 await getRecipes()로 목록을 받아 서버에서 셉니다(1절).

  • ① Count는 이 레슨에서 지웠습니다.
  • ② 쪽에 클라이언트 컴포넌트가 없어, 브라우저에서 다시 세는 코드가 없습니다.

문제 2. 목록에서 별을 바꾸면 통계 쪽의 즐겨찾기 수가 새로 세어지는 까닭은 무엇일까요?

  • ① toggleFavorite가 통계 쪽도 쓰는 'recipes' 기억을 지운다
  • ② 통계 쪽은 아무것도 기억하지 않는다
  • ③ 별 단추가 통계 쪽을 다시 부른다
정답

①입니다. 목록 · 자세히 · 통계가 모두 'recipes' 이름표의 기억을 씁니다(2절).

  • ② 통계 쪽은 getRecipes가 기억한 목록으로 셉니다. 경로 표의 1h · 1d가 그 표시입니다(예제).
  • ③ 별 단추는 toggleFavorite만 부릅니다. 통계 쪽은 다음에 열 때 그려집니다.

문제 3. '백업 내려받기'를 누르면 탭에 그리지 않고 파일로 받게 하는 것은 무엇일까요?

  • ① <a>의 href
  • ② 응답 머리 Content-Disposition
  • ③ 주소 끝의 /api
정답

②입니다. 경로 처리기가 머리에 attachment와 파일 이름을 적었습니다(해 보기).

  • ① href는 갈 주소일 뿐입니다. 받는 꼴은 응답이 정합니다.
  • ③ /api는 폴더 이름입니다. 이름이 받는 꼴을 정하지 않습니다.
이 레슨에서 바꾼 파일

components/Count.tsx — 지웁니다(셈은 쪽에서).

app/stats/page.tsx — 서버에서 셈 · 내보내기 링크

app/stats/page.tsx
import type {
  Metadata,
} from 'next';
import {
  categories,
  getRecipes,
} from '@/lib/recipes';
import styles from
  './page.module.css';

export const
  metadata: Metadata = {
    title: '통계',
  };

async function Page() {
  // 1. 기억한 목록 읽기
  const recipes =
    await getRecipes();
  // 2. 서버에서 셈하기
  const total = recipes.length;
  const sum = recipes.reduce(
    (s, r) => s + r.minutes,
    0,
  );
  const average =
    total === 0
      ? 0
      : Math.round(sum / total);
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  const countOf = (c: string) =>
    recipes.filter(
      (r) => r.category === c,
    ).length;
  const rows = categories.map(
    (c) => (
      <li key={c}>
        {c} {countOf(c)}개
      </li>
    ),
  );
  return (
    <>
      <h1
        className={styles.card}
      >
        통계
      </h1>
      <p>전체 {total}개</p>
      <p>평균 {average}분</p>
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <ul>{rows}</ul>
      {/* 3. 내보내기 링크 */}
      <a href="/api/recipes">
        백업 내려받기
      </a>
    </>
  );
}

export default Page;
이 단원 끝 파일

단원 9에서 바꾼 파일을 모두 끝 판으로 모았습니다. 건너뛴 레슨이 있으면 지울 파일 다섯(app/boom/page.tsx · app/boom/error.tsx · components/Show.tsx · app/recipes/page.module.css · components/Count.tsx)을 지우고, 아래 열셋을 붙여 넣습니다.

app/page.tsx

app/page.tsx
export default function Home() {
  return <h1>레시피 보관함</h1>;
}

app/layout.tsx

app/layout.tsx
import type {
  Metadata,
} from 'next';
import Image from 'next/image';
import {
  Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
  '@/components/TabBar';

const noto = Noto_Sans_KR({
  subsets: ['latin'],
});

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body
        className={
          noto.className
        }
      >
        <TabBar />
        {children}
        <footer>
          바닥글
          <Image
            src="/next.svg"
            alt="Next.js"
            width={100}
            height={20}
          />
        </footer>
      </body>
    </html>
  );
}

export default RootLayout;

components/RecipeCard.tsx

components/RecipeCard.tsx
import Link from 'next/link';
import FavoriteButton from
  './FavoriteButton';
import type {
  Recipe,
} from '@/lib/recipes';
import styles from
  './RecipeCard.module.css';

function RecipeCard({
  recipe,
}: {
  recipe: Recipe;
}) {
  const href =
    '/recipes/' + recipe.id;
  return (
    <li className={styles.card}>
      <Link href={href}>
        {recipe.title}
      </Link>
      <span>
        {recipe.minutes}분
      </span>
      <FavoriteButton
        recipe={recipe}
      />
    </li>
  );
}

export default RecipeCard;

components/의 RecipeCard.module.css

components/RecipeCard.module.css
.card {
  padding: 8px;
  border-top: 1px solid #ccc;
}

components/CategoryFilter.tsx

components/CategoryFilter.tsx
import Link from 'next/link';
import {
  categories,
} from '@/lib/recipes';

const choices = [
  '전체',
  ...categories,
];

// 5. 분류 링크
const hrefOf = (c: string) =>
  c === '전체'
    ? '/recipes'
    : '/recipes?category=' + c;

function CategoryFilter({
  category,
}: {
  category: string;
}) {
  const mark = (c: string) =>
    c === category ? '▸ ' : '';
  const links = choices.map(
    (c) => (
      <Link
        key={c}
        href={hrefOf(c)}
      >
        {mark(c)}
        {c}{' '}
      </Link>
    ),
  );
  return <p>{links}</p>;
}

export default CategoryFilter;

components/RecipeList.tsx

components/RecipeList.tsx
import CategoryFilter from
  './CategoryFilter';
import RecipeCard from
  './RecipeCard';
import {
  categories,
  getRecipes,
  type Recipe,
} from '@/lib/recipes';

type Value =
  string | string[] | undefined;

const one = (v: Value) =>
  typeof v === 'string'
    ? v
    : '';

const byTime = (
  a: Recipe,
  b: Recipe,
) => a.minutes - b.minutes;

// 1. 기다리는 일을 자식으로
async function RecipeList({
  searchParams,
}: {
  searchParams: Promise<{
    q?: Value;
    category?: Value;
    sort?: Value;
  }>;
}) {
  // 2. 자식에서 await로 읽기
  const query =
    await searchParams;
  const word = one(query.q);
  const picked = one(
    query.category,
  );
  const category =
    categories.includes(picked)
      ? picked
      : '전체';
  const recipes =
    await getRecipes();
  const found = recipes
    .filter((r) =>
      r.title.includes(word),
    )
    .filter(
      (r) =>
        category === '전체' ||
        r.category === category,
    );
  // 6. 정렬
  const sort = one(query.sort);
  const shown =
    sort === 'fastest'
      ? found.toSorted(byTime)
      : found;
  return (
    <>
      <CategoryFilter
        category={category}
      />
      <ul>
        {shown.map((r) => (
          <RecipeCard
            key={r.id}
            recipe={r}
          />
        ))}
      </ul>
    </>
  );
}

export default RecipeList;

app/recipes/page.tsx

app/recipes/page.tsx
import {
  Suspense,
} from 'react';
import Link from 'next/link';
import type {
  Metadata,
} from 'next';
import SearchBar from
  '@/components/SearchBar';
import RecipeList from
  '@/components/RecipeList';

export const
  metadata: Metadata = {
    title: '목록',
  };

const fastest =
  '/recipes?sort=fastest';

// 3. 쪽에서 Suspense로 감싸기
function Page({
  searchParams,
}: PageProps<'/recipes'>) {
  return (
    <>
      {/* 4. 찾기 칸 */}
      <SearchBar />
      <Link href="/recipes/new">
        새 레시피
      </Link>
      <Link href={fastest}>
        빠른 순
      </Link>
      <Suspense
        fallback={
          <p>목록을 읽는 중</p>
        }
      >
        <RecipeList
          searchParams={
            searchParams
          }
        />
      </Suspense>
    </>
  );
}

export default Page;

app/recipes/[id]/page.tsx

app/recipes/[id]/page.tsx
import {
  Suspense,
} from 'react';
import {
  notFound,
} from 'next/navigation';
import {
  getRecipe,
  getRecipes,
} from '@/lib/recipes';
import Fold from
  '@/components/Fold';

// 1. 빌드 때 그릴 id 알려 주기
export const
  generateStaticParams =
    async () => {
      const list =
        await getRecipes();
      return list.map((r) => ({
        id: r.id,
      }));
    };

export const
  generateMetadata = async ({
    params,
  }: {
    params: Promise<{
      id: string;
    }>;
  }) => {
    const { id } = await params;
    const found =
      await getRecipe(id);
    return {
      title: found?.title,
    };
  };

function Ingredients({
  items,
}: {
  items: string[];
}) {
  return (
    <ul>
      {items.map((i) => (
        <li key={i}>{i}</li>
      ))}
    </ul>
  );
}

async function RecipeDetail({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  // 2. 주소의 id 꺼내기
  const { id } = await params;
  // 3. 찾고, 없으면 없는 쪽
  const found =
    await getRecipe(id);
  if (!found) {
    notFound();
  }
  // 4. 레시피 그리기
  const items =
    found.ingredients;
  return (
    <>
      <h2>{found.title}</h2>
      <p>{found.category}</p>
      <p>{found.minutes}분</p>
      {/* 5. 재료 접기 */}
      <Fold>
        <Ingredients
          items={items}
        />
      </Fold>
    </>
  );
}

function Page({
  params,
}: PageProps<'/recipes/[id]'>) {
  return (
    <Suspense
      fallback={
        <p>레시피를 읽는 중</p>
      }
    >
      <RecipeDetail
        params={params}
      />
    </Suspense>
  );
}

export default Page;

app/recipes/new/page.tsx

app/recipes/new/page.tsx
import type {
  Metadata,
} from 'next';
import RecipeForm from
  '@/components/RecipeForm';
import {
  categories,
} from '@/lib/recipes';

export const
  metadata: Metadata = {
    title: '새 레시피',
  };

function Page() {
  return (
    <RecipeForm
      categories={categories}
    />
  );
}

export default Page;

lib/recipes.ts

lib/recipes.ts
import {
  readFile,
  writeFile,
} from 'node:fs/promises';
import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export interface Recipe {
  id: string;
  title: string;
  category: string;
  minutes: number;
  ingredients: string[];
  favorite: boolean;
}

export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

function isRecipe(
  v: unknown,
): v is Recipe {
  return (
    typeof v === 'object' &&
    v !== null &&
    'id' in v &&
    'title' in v &&
    'category' in v &&
    'minutes' in v &&
    'ingredients' in v &&
    'favorite' in v &&
    typeof v.id === 'string' &&
    typeof v.title ===
      'string' &&
    typeof v.category ===
      'string' &&
    typeof v.minutes ===
      'number' &&
    Array.isArray(
      v.ingredients,
    ) &&
    typeof v.favorite ===
      'boolean'
  );
}

// 1. 함수 머리에 'use cache'
export const getRecipes =
  async () => {
    'use cache';
    // 2. cacheLife로 얼마나
    cacheLife('hours');
    // 3. cacheTag로 이름 붙이기
    cacheTag('recipes');
    console.log(
      '레시피 파일 읽음',
    );
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    return Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  };

export const getRecipe =
  async (id: string) => {
    'use cache';
    cacheLife('hours');
    cacheTag('recipes');
    console.log(
      '레시피 하나 읽음',
      id,
    );
    const list =
      await getRecipes();
    return list.find(
      (r) => r.id === id,
    );
  };

// 기억한 목록이 아니라 파일을 읽음
export const addRecipe = async (
  input: {
    title: string;
    category: string;
    minutes: number;
  },
) => {
  const text = await readFile(
    'data/recipes.json',
    'utf8',
  );
  const data: unknown =
    JSON.parse(text);
  const list: Recipe[] =
    Array.isArray(data)
      ? data.filter(isRecipe)
      : [];
  const recipe: Recipe = {
    id: crypto.randomUUID(),
    ...input,
    ingredients: [],
    favorite: false,
  };
  list.push(recipe);
  await writeFile(
    'data/recipes.json',
    JSON.stringify(
      list, null, 2,
    ),
  );
  return recipe;
};

// 파일을 읽어 그 레시피의 별만 바꿈
export const updateFavorite =
  async (
    id: string,
    favorite: boolean,
  ) => {
    const text = await readFile(
      'data/recipes.json',
      'utf8',
    );
    const data: unknown =
      JSON.parse(text);
    const list: Recipe[] =
      Array.isArray(data)
        ? data.filter(isRecipe)
        : [];
    const next = list.map((r) =>
      r.id === id
        ? { ...r, favorite }
        : r,
    );
    await writeFile(
      'data/recipes.json',
      JSON.stringify(
        next, null, 2,
      ),
    );
  };

app/actions.ts

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
  categories,
  updateFavorite,
} from '@/lib/recipes';

async function createRecipe(
  prevState: { error: string },
  formData: FormData,
) {
  // 2. 값 꺼내 검사하기
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    title.trim() === ''
  ) {
    return {
      error: '이름을 적어 주세요',
    };
  }
  if (title.length > 30) {
    return {
      error: '이름은 30자까지',
    };
  }
  if (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  if (
    !categories.includes(
      category,
    )
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  const minutes = Number(
    formData.get('minutes'),
  );
  if (
    minutes < 1 ||
    !Number.isInteger(minutes)
  ) {
    return {
      error: '분은 1 이상 정수로',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes,
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

async function toggleFavorite(
  id: string,
  favorite: boolean,
) {
  // 2. 값 꺼내 검사하기
  if (
    typeof id !== 'string' ||
    typeof favorite !==
      'boolean'
  ) {
    throw new Error('잘못된 값');
  }
  // 3. 저장하기
  await updateFavorite(
    id,
    favorite,
  );
  // 4. 기억 지우기
  updateTag('recipes');
}

export {
  createRecipe,
  toggleFavorite,
};

components/FavoriteButton.tsx

components/FavoriteButton.tsx
// 1. 경계 표시와 import
'use client';

import {
  useOptimistic,
} from 'react';
import {
  toggleFavorite,
} from '@/app/actions';
import type {
  Recipe,
} from '@/lib/recipes';

function FavoriteButton({
  recipe,
}: {
  recipe: Recipe;
}) {
  // 2. 별을 낙관 값으로 두기
  const [starred, setStarred] =
    useOptimistic(
      recipe.favorite,
    );
  // 3. 누르면 서버 함수로 저장
  async function handleStar() {
    setStarred(!starred);
    await toggleFavorite(
      recipe.id,
      !starred,
    );
  }
  // 4. 별 그리기
  return (
    <form action={handleStar}>
      <button>
        {starred ? '★' : '☆'}
      </button>
    </form>
  );
}

export default FavoriteButton;

app/stats/page.tsx

app/stats/page.tsx
import type {
  Metadata,
} from 'next';
import {
  categories,
  getRecipes,
} from '@/lib/recipes';
import styles from
  './page.module.css';

export const
  metadata: Metadata = {
    title: '통계',
  };

async function Page() {
  // 1. 기억한 목록 읽기
  const recipes =
    await getRecipes();
  // 2. 서버에서 셈하기
  const total = recipes.length;
  const sum = recipes.reduce(
    (s, r) => s + r.minutes,
    0,
  );
  const average =
    total === 0
      ? 0
      : Math.round(sum / total);
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  const countOf = (c: string) =>
    recipes.filter(
      (r) => r.category === c,
    ).length;
  const rows = categories.map(
    (c) => (
      <li key={c}>
        {c} {countOf(c)}개
      </li>
    ),
  );
  return (
    <>
      <h1
        className={styles.card}
      >
        통계
      </h1>
      <p>전체 {total}개</p>
      <p>평균 {average}분</p>
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <ul>{rows}</ul>
      {/* 3. 내보내기 링크 */}
      <a href="/api/recipes">
        백업 내려받기
      </a>
    </>
  );
}

export default Page;

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

Next.js 목차로