TypeScript SDK
FoodForCMS の公式 TypeScript SDK で型付きコンテンツを取得するガイド。エントリーの一覧・一件取得、オブジェクト取得、全件取得、再試行、エラー処理を説明します。
foodforcms は公開 API 用の公式 TypeScript クライアントです。公開エントリーの読み取り専用で、コンテンツの作成や更新はできません。ESM と CommonJS の両方に対応し、fetch を使える環境(Node.js、ブラウザ、Workers など)で動作します。
API キーはサーバー側で管理し、ブラウザに配信されるコードには含めないでください。
インストール
pnpm add foodforcms
# npm install foodforcms
クイックスタート
プロジェクトの 設定 → API Keys でキーを発行し、キーに紐づくプロジェクトの ID(proj_ で始まる文字列)とともに渡します。
import { createClient } from "foodforcms";
const client = createClient({
apiKey: process.env.FOODFORCMS_API_KEY!,
projectId: "proj_xxxx",
});
const { data, total } = await client.getList("blog_posts");
console.log(total, data[0]?.data);
new FoodForCMS(options) でも同じクライアントを作成できます。
設定
| オプション | 型 | 既定値 | 説明 |
|---|---|---|---|
apiKey |
string |
— | 必須。 ダッシュボードで発行した API キー。 |
projectId |
string |
— | 必須。 API キーに紐づくプロジェクトの ID。 |
baseUrl |
string |
FoodForCMS の API | 接続先のオリジンを変更する場合に指定します。 |
retry |
boolean | { maxRetries?: number } |
true(2 回) |
再試行の設定。false で無効になります。 |
再試行の対象は 429、500、502、503、504 とネットワーク障害です。Retry-After ヘッダーがあればその秒数だけ待ち、なければ 0.5 秒、1 秒、2 秒…と間隔を延ばします。中断済みの signal を渡したリクエストは再試行しません。
const client = createClient({
apiKey: process.env.FOODFORCMS_API_KEY!,
projectId: "proj_xxxx",
retry: { maxRetries: 3 },
});
コレクションの型付け
コレクションの apiId をキー、data の型を値とするスキーマ型を渡すと、コレクション名、fields、populate、filters、sort が型検査され、fields で戻り値の型も絞られます。
import { createClient } from "foodforcms";
import type { MediaValue, RichTextValue } from "foodforcms";
interface Recipe {
title: string;
slug: string;
cooking_time?: number;
body?: RichTextValue; // { html: string; json: string }
cover?: MediaValue; // { id: string; url: string }
}
interface SiteSettings {
site_name: string;
}
const client = createClient<{ recipes: Recipe; site_settings: SiteSettings }>({
apiKey: process.env.FOODFORCMS_API_KEY!,
projectId: "proj_xxxx",
});
const { data } = await client.getList("recipes", { fields: ["title", "slug"] });
data[0]?.data.title; // string
data[0]?.data.cooking_time; // 型エラー: fields で選択していない
await client.getList("recipe"); // 型エラー: 存在しないコレクション
スキーマ型を渡さない場合は任意のコレクション名を受け付け、data は EntryData 型になります。
メソッド
| メソッド | 対象 | 戻り値 |
|---|---|---|
getList(apiId, params?, options?) |
リスト | 一ページ分:{ data, page, limit, total } |
getEntry(apiId, id, params?, options?) |
リスト | エントリー一件 |
getObject(apiId, params?, options?) |
オブジェクト | コレクションのエントリー |
getAllEntries(apiId, params?, options?) |
リスト | 条件に一致するすべてのエントリー |
getAllEntryIds(apiId, params?, options?) |
リスト | 条件に一致するすべてのエントリー ID |
どのメソッドも、公開中のエントリーと公開日時を過ぎた予約投稿だけを返します。
getList
const { data, page, limit, total } = await client.getList("recipes", {
page: 1,
limit: 20, // 1〜100、既定 20
filters: {
title: { contains: "パン" },
cooking_time: { lessThan: 30 },
},
sort: "publishedAt", // "createdAt"、"updatedAt"、またはフィールドの API ID
order: "desc", // 既定 "desc"
fields: ["title", "slug", "cooking_time"], // data に含めるフィールド
ids: ["entry_abc", "entry_def"], // 指定した ID のみ(最大 100 件)
});
total はページ内の件数ではなく、条件に一致する総数です。
フィルターの演算子は equals、contains(大文字小文字を区別しない部分一致)、greaterThan、lessThan(数値・日付フィールドのみ)です。SDK がそれぞれ API の equals、contains、greater_than、less_than に変換します。複数の条件はすべて満たす必要があります。詳しくはコンテンツ APIをご覧ください。
getEntry
const recipe = await client.getEntry("recipes", "entry_abc", {
fields: ["title", "body"],
});
下書き、公開日時前の予約投稿、存在しない ID には 404 の FoodForCMSError をスローします。
getObject
kind: object のコレクション(サイト設定など)は一件のエントリーを持ちます。
const settings = await client.getObject("site_settings");
console.log(settings.data.site_name);
エントリーが未公開の間は 404、リスト形式のコレクションにはコード not_object_collection の 400 になります。
getAllEntries
100 件ずつのページを順番に取得して、すべてのエントリーを返します。並列に取得しないため、API キーのレート制限を超えにくくなっています。filters、sort、order、fields、populate を受け取ります。
const breads = await client.getAllEntries("recipes", {
filters: { title: { contains: "パン" } },
fields: ["title", "slug"],
});
getAllEntryIds
ID だけを 1000 件ずつ取得します。静的ページのパス生成などに使えます。filters、sort、order を受け取ります。
// Next.js App Router
export const generateStaticParams = async () => {
const ids = await client.getAllEntryIds("recipes");
return ids.map((id) => ({ id }));
};
参照の展開
populate に参照フィールドの API ID を指定すると、ID が公開中の参照先エントリーに置き換わります(一階層のみ)。getList、getEntry、getObject、getAllEntries で使えます。
import type { Entry } from "foodforcms";
interface Category {
name: string;
}
interface Post {
title: string;
// populate しない場合は ID、した場合はエントリー(非公開なら null)
category?: string | Entry<Category> | null;
}
const posts = createClient<{ posts: Post }>({
apiKey: process.env.FOODFORCMS_API_KEY!,
projectId: "proj_xxxx",
});
const { data } = await posts.getList("posts", { populate: ["category"] });
SDK は populate の有無で値の型を切り替えません。展開して使う参照フィールドは、上の例のように両方の形を許す型にしてください。
エントリーの型
interface Entry<TData> {
id: string;
collectionId: string;
status: "published";
data: TData; // フィールドの API ID をキーとする値
publishedAt: string | null;
createdAt: string;
updatedAt: string;
}
data の値の型は次のとおりです。値が空のフィールドはキーごと省略されるため、必須でないフィールドは省略可能なプロパティにしてください。
| フィールドタイプ | TypeScript の型 |
|---|---|
text、date |
string |
number |
number |
boolean |
boolean |
select、reference |
string、または multiple のとき string[] |
richtext |
RichTextValue({ html, json }) |
media |
MediaValue({ id, url }) |
SDK が公開する型は Entry、EntryData、EntryFieldValue、EntryList、EntryFilterOperators、FieldName、FilterSortParams、FoodForCMSOptions、GetListParams、GetEntryParams、GetAllEntriesParams、GetAllEntryIdsParams、MediaValue、RichTextValue、RequestOptions、RetryOptions です。
リクエストオプション
すべてのメソッドは最後の引数に { fetchOptions } を受け取り、fetch にそのまま渡します。ただし method と x-api-key ヘッダーは SDK が設定します。
// リクエストを中断する
const controller = new AbortController();
await client.getList("recipes", {}, { fetchOptions: { signal: controller.signal } });
// Next.js のキャッシュ
await client.getObject("site_settings", {}, { fetchOptions: { next: { revalidate: 60 } } });
エラーハンドリング
API がエラーを返すと FoodForCMSError をスローします。status(HTTP ステータス)、code(API が返した場合の識別コード)、message を参照できます。catch では isFoodForCMSError で判定してください。
import { isFoodForCMSError } from "foodforcms";
try {
await client.getEntry("recipes", "entry_missing");
} catch (error) {
if (isFoodForCMSError(error)) {
console.error(error.status); // 404
console.error(error.message); // "Entry not found"
console.error(error.code); // undefined、または "rate_limited" など
}
}
再試行しても解消しなかったネットワーク障害は、fetch のエラーがそのままスローされます。レスポンスが JSON でない場合は FoodForCMSError(メッセージ Response is not JSON)になります。
| HTTP ステータス | 主な理由 |
|---|---|
| 400 | API キーがない、クエリパラメータが無効、またはリスト形式のコレクションに getObject を使用(not_object_collection) |
| 401 | API キーが無効または期限切れ |
| 403 | projectId がキーのプロジェクトと異なる |
| 404 | コレクションまたは公開エントリーが見つからない、またはキーでアクセスが許可されていない |
| 429 | レート制限(キーごとに毎秒 60 リクエスト)を超えた(rate_limited) |
| 500 | サーバーエラー |
次のステップ
コンテンツ APIでデータモデルとクエリを、API リファレンスでパラメータとレスポンスの詳細を確認してください。