Kanorio

開始使用

Next.js 與 Cache Components

在 "use cache" 函式中讀取 Kanorio 內容,從回應中標記每次讀取,並一次重新整理單筆記錄。

當設定 cacheComponents: true 時,Next.js 會快取您標記為 "use cache" 的內容,並允許您在讀取後加入快取標籤。Kanorio 的回應會列出其專屬標籤,因此文章會被標記為其自身的 item:<id>,編輯單篇文章時僅會重新整理該文章及其所屬的列表,其餘內容皆不會重新擷取。

本頁面取代了 Next.js 指南 中的步驟 3 與步驟 4。環境變數、產生的型別、Webhook 路由、草稿模式以及 SEO 檔案皆維持不變。

1. 啟用功能

// next.config.ts
import { seoRewrites } from "@kanorio/sdk";

export default {
  cacheComponents: true,
  async rewrites() {
    return seoRewrites({ siteUrl: process.env.NEXT_PUBLIC_KANORIO_SITE_URL!, framework: "next" });
  },
};

2. 在 "use cache" 中讀取

// lib/kanorio.ts
import { cacheLife, cacheTag } from "next/cache";
import { draftMode } from "next/headers";
import { frameworkCacheTags } from "@kanorio/sdk";

const SITE_URL = process.env.NEXT_PUBLIC_KANORIO_SITE_URL!;

export async function kanorio<T>(path: string): Promise<T | null> {
  "use cache";
  cacheLife("hours");
  const { isEnabled: isDraft } = await draftMode();
  const url = new URL(`/api/v1${path}`, SITE_URL);
  if (isDraft) url.searchParams.set("preview", "1");

  const res = await fetch(url, isDraft ? { headers: { "X-Kanorio-Preview": process.env.KANORIO_PREVIEW_TOKEN! } } : undefined);
  // The response lists what it used; tag after the read
  cacheTag(...frameworkCacheTags(res.headers));
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Kanorio ${res.status} for ${path}`);
  return (await res.json()) as T;
}

frameworkCacheTags 會讀取 X-Kanorio-Cache-Tags 並加入 Webhook 處理常式所使用的 kanorio: 前綴。cacheLife("hours") 是針對 Webhook 未送達時的備援機制。當草稿模式開啟時,Next.js 會在每次請求時執行快取函式且不儲存任何內容,因此草稿內容永遠是最新的。

3. 渲染文章

列表頁面無需傳遞任何參數,僅需路徑:

// app/blog/page.tsx
import Link from "next/link";
import { image } from "@kanorio/sdk";
import { kanorio } from "@/lib/kanorio";
import type { KanorioCollectionsMap } from "@/types/kanorio";

export default async function BlogIndex() {
  const page = await kanorio<KanorioCollectionsMap["blog"]["list"]>(
    "/collections/blog/items?sort=-publishedAt&limit=20&fields=title,excerpt,cover_image,share_image"
  );
  return (
    <ul>
      {page?.data.map((post) => {
        // The cover the author picked, resized for a card. A post without one shows its share image (1200x630, ready to use)
        const cover = image.resolve(post.fieldData.cover_image, page.assets);
        const src = cover ? image.url(cover.url, { width: 800 }) : post.fieldData.share_image?.url;
        return (
          <li key={post.id}>
            {src && <img src={src} alt={cover?.alt ?? ""} loading="lazy" />}
            <Link href={post.path ?? `/blog/${post.slug}`}>{post.fieldData.title}</Link>
          </li>
        );
      })}
    </ul>
  );
}

針對文章頁面,請在 generateStaticParams 中列出文章。Next.js 會在建置時預先渲染這些頁面,並在首次造訪時渲染後續發佈的文章;若 slug 不存在,則會回傳真實的 404 狀態:

// app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { image, seoMetadata } from "@kanorio/sdk";
import { toNextMetadata } from "@kanorio/sdk/next";
import { kanorio } from "@/lib/kanorio";
import type { KanorioCollectionsMap } from "@/types/kanorio";

type Params = { params: Promise<{ slug: string }> };

function loadPost(slug: string) {
  return kanorio<KanorioCollectionsMap["blog"]["single"]>(
    `/collections/blog/items/${encodeURIComponent(slug)}?expand=authors,categories&formats=html`
  );
}

export async function generateStaticParams() {
  const page = await kanorio<KanorioCollectionsMap["blog"]["list"]>("/collections/blog/items?sort=-publishedAt&limit=100&fields=title");
  return (page?.data ?? []).map((post) => ({ slug: post.slug }));
}

export async function generateMetadata({ params }: Params): Promise<Metadata> {
  const data = await loadPost((await params).slug);
  if (!data) return {};
  // Title, description, canonical, robots and the share image, by the rules the hosted site uses.
  // The share image is `fieldData.share_image`: Kanorio has picked it and cropped it the way the author framed it
  return toNextMetadata(seoMetadata(data.item));
}

export default async function BlogPost({ params }: Params) {
  const data = await loadPost((await params).slug);
  if (!data) notFound();

  const { item, assets } = data;
  // The cover is optional. It is an asset id: `assets` has its URL, size and alt text
  const cover = image.resolve(item.fieldData.cover_image, assets);
  return (
    <article>
      <h1>{item.fieldData.title}</h1>
      {cover && (
        <img
          src={image.url(cover.url, { width: 1200 })}
          srcSet={image.srcSet(cover.url)}
          sizes="(min-width: 800px) 768px, 100vw"
          alt={cover.alt ?? ""}
          width={cover.width ?? undefined}
          height={cover.height ?? undefined}
        />
      )}
      {item.contentHtml && <div dangerouslySetInnerHTML={{ __html: item.contentHtml }} />}
    </article>
  );
}

列表與文章頁面處理封面的方式與 Next.js 指南 相同:cover_image 是作者選擇的封面,沒有時為 null。列表在沒有封面時改用 share_image,文章頁面在文章有封面時顯示它,generateMetadata 則由 seoMetadata 取得標題、標準網址、robots 與分享圖片。

generateMetadata 與頁面會使用相同的參數呼叫 loadPost,因此文章僅會被讀取一次。若沒有 generateStaticParams,頁面必須在 <Suspense> 內讀取 params;雖然這樣也能建置,但當系統查詢文章時回應已經開始,因此遺失的文章會以 200 狀態碼送出。

4. 重新驗證

請保留 Next.js 指南步驟 5 中的路由處理常式。它會重新驗證事件所列出的每個標籤;透過上述標籤,item:<id> 現在會精確對應到單一文章。