サイトの表示を作る(通しの例)
この記事の内容
公開トークンで全件を取り込み、公開のたびに作り直す
Kumidana は
このnews(title、slug、body)と、kmd_pub_ の
- ビルドの
ときに、 公開トークンで 一覧を 全件取り込む。 htmlとtextを使い分けて 描画する。 - 公開と
取り下げの Webhook で、 再ビルドを 起動する。 - 下書きの
プレビューは、 サーバー側で プレビュートークンを 使って 表示する。 - 会員限定の
内容が 要る ときだけ、 閲覧者の トークンを 添える。
1. 全件を取り込む
limit はoffset をtotal に
// src/lib/kumidana.ts
const BASE = `https://api.kumidana.com/v1/${process.env.KUMIDANA_SITE}`;
const headers = { Authorization: `Bearer ${process.env.KUMIDANA_TOKEN}` };
export type Entry<T> = {
id: string;
type: string;
slug: string | null;
publishedAt: string | null;
updatedAt: string;
data: T;
};
export async function api<T>(path: string, params: Record<string, string> = {}): Promise<T> {
const url = `${BASE}${path}?${new URLSearchParams(params)}`;
const res = await fetch(url, { headers });
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new Error(`${res.status} ${body?.error?.code ?? ''} ${url}`);
}
return res.json() as Promise<T>;
}
/** 一覧を全件取り込む。limit は 100 が上限 */
export async function fetchAll<T>(type: string, params: Record<string, string> = {}): Promise<Entry<T>[]> {
const all: Entry<T>[] = [];
for (let offset = 0; ; offset += 100) {
const page = await api<{ items: Entry<T>[]; total: number }>(`/content/${type}`, {
...params,
limit: '100',
offset: String(offset),
});
all.push(...page.items);
if (offset + 100 >= page.total) return all;
}
}KUMIDANA_SITE にKUMIDANA_TOKEN にkmd_pub_ の
並べ替えとorder にpublishedAt、updatedAt と、indexed をunique のslugField の
const news = await fetchAll<NewsData>('news', { order: '-publishedAt' });2. 描画する
テキストのtext とhtml をmarkdown とhtml をurl、alt、width、height を
// src/lib/kumidana.ts に追記する
export type NewsData = {
title: { text: string; html: string };
slug: string;
// 本文は必須にしていないと null になる
body: { markdown: string; html: string } | null;
// 画像の項目 cover を種類に足した場合
cover?: { url: string; alt: string; width: number | null; height: number | null } | null;
};使い分けはhtml を、<title> やtext をhtml は<wbr> が
const esc = (s: string) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
export function renderNews(e: Entry<NewsData>): string {
const { title, body, cover } = e.data;
return `<!doctype html>
<html lang="ja">
<head><title>${esc(title.text)}</title></head>
<body>
<h1>${title.html}</h1>
${cover ? `<img src="${esc(cover.url)}" alt="${esc(cover.alt)}" width="${cover.width ?? ''}" height="${cover.height ?? ''}">` : ''}
${body?.html ?? ''}
</body>
</html>`;
}画像のurl(https://media.kumidana.com/...)は
参照と single の種類
別のdepth=1 で、data までdepth=2 をdepth=0 にnull に
single の/content/<種類のキー> が
type SiteData = { tagline: { text: string; html: string } };
const site = await api<Entry<SiteData>>('/content/site'); // 「site」は自分で作った single の種類3. 公開のたびに作り直す
エントリーのentry.published とentry.unpublished にtype とentryId、slug だけが
// Cloudflare Workers の例。verifyWebhook は「署名を検証する」のページの関数
import { verifyWebhook } from './verify-webhook';
export default {
async fetch(request: Request, env: { WEBHOOK_SECRET: string; DEPLOY_HOOK_URL: string }) {
const raw = await request.text();
if (!(await verifyWebhook(env.WEBHOOK_SECRET, raw, request.headers.get('x-kumidana-signature')))) {
return new Response('invalid signature', { status: 401 });
}
const { event } = JSON.parse(raw);
if (event === 'entry.published' || event === 'entry.unpublished') {
const deploy = await fetch(env.DEPLOY_HOOK_URL, { method: 'POST' });
// 起動できなかったときは 2xx 以外を返し、Kumidana に再試行させる
if (!deploy.ok) return new Response('再ビルドを起動できませんでした', { status: 502 });
}
return new Response(null, { status: 204 });
},
};署名の
公開してから
4. 下書きをプレビューする
公開前のkmd_pre_)で
export async function fetchPreview<T>(type: string, id: string): Promise<Entry<T>> {
const res = await fetch(`${BASE}/content/${type}/${id}?draft=1`, {
headers: { Authorization: `Bearer ${process.env.KUMIDANA_PREVIEW_TOKEN}` },
});
if (!res.ok) throw new Error(`${res.status}`);
return res.json();
}管理画面のkmd_pvw_)をCache-Control: private, no-store とnoindex を
5. 会員限定の内容を出す
閲覧グループでkmd_vat_)をKumidana-Viewer ヘッダーでBearer は
export async function fetchAsViewer<T>(path: string, viewerToken: string): Promise<Response> {
return fetch(`${BASE}${path}`, {
headers: { ...headers, 'Kumidana-Viewer': viewerToken },
});
}ログインの
キャッシュの決まり
| 読み方 | 保存してよい |
|---|---|
| 公開トークンだけ |
共有キャッシュも |
| カスタムの |
ブラウザだけ。 |
プレビューdraft=1、ref=) |
保存しない |
Kumidana-Viewer 付き |
保存しない |
閲覧者付きのKumidana-Viewer なしで
サーバー側でAuthorization をfields は
Astro で使うとき
Astro のgetStaticPaths でfetchAll を
---
// src/pages/news/[slug].astro
import { fetchAll, type NewsData } from '../../lib/kumidana';
export async function getStaticPaths() {
const entries = await fetchAll<NewsData>('news');
// slug が null のエントリーはページにしない
return entries.flatMap((entry) => (entry.slug ? [{ params: { slug: entry.slug }, props: { entry } }] : []));
}
const { entry } = Astro.props;
---
<h1 set:html={entry.data.title.html} />
<div set:html={entry.data.body?.html ?? ''} />トークンは、.env にKUMIDANA_TOKEN とexport const prerender = false; を
困ったとき
- 401 の
ときは、 トークンの 打ち間違い、 期限切れ、 取り消し、 付け忘れ、 サイトの 停止を 確かめます。 トークンと URL の サイトが 違う 場合は 404 に なります。 - 一覧に
出ない エントリーは、 まだ 公開していないか、 閲覧グループで 限定されています。 - 429 が
返るなら、 Retry-Afterの秒数だけ 待ちます。 同じ データの 再取得を まとめる、 公開分を キャッシュする、 limit=100でまとめて 取るなどして、 呼び出しの 回数を 減らします。 fieldsは通信量を 減らしますが、 回数制限の カウントは 減りません。