TypeScript SDK
@todoke/sdk を使うと、購読登録から通知送信まで数行で実装できます。
インストール
Section titled “インストール”npm install @todoke/sdkbun add @todoke/sdkpnpm add @todoke/sdkクライアントの初期化
Section titled “クライアントの初期化”import { PushCF } from "@todoke/sdk";
const client = new PushCF({ apiKey: "pk_your_key", // baseUrl: "https://api.todoke.dev" // デフォルト値});メソッドリファレンス
Section titled “メソッドリファレンス”PushCF インスタンスは以下の 3 つのメソッドを提供します。
| メソッド | 説明 | 必要スコープ |
|---|---|---|
notify(payload: NotifyPayload): Promise<void> | 通知を送信する(POST /api/v1/notify) | notify 以上 |
subscribe({ registration }: SubscribeOptions): Promise<void> | ブラウザの Push 購読を登録する | subscribe_only 以上 |
getStats(): Promise<Stats> | 統計情報を取得する(GET /api/v1/stats) | notify 以上 |
// Service Worker の準備(事前に /sw.js を配置)const registration = await navigator.serviceWorker.ready;
// 購読登録(ブラウザ通知許可ダイアログが表示される)await client.subscribe({ registration });subscribe は内部で次の 3 段階の処理を順に行います。
GET /api/v1/vapid-public-keyを呼び出し、アプリの VAPID 公開鍵を取得する- 取得した鍵を
applicationServerKeyとしてregistration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey })を呼び出す(ここでブラウザの通知許可ダイアログが表示される) - 作成された購読情報(
endpoint/p256dh/auth)をPOST /api/v1/subscriptionsでサーバーに登録する
// 全購読者へ送信await client.notify({ title: "お知らせ", body: "新しいメッセージがあります", url: "https://yourapp.com/messages", icon: "https://yourapp.com/icon.png",});
// 特定の購読者へ送信await client.notify({ title: "あなた宛", body: "個別通知", endpoint: "https://push.example.com/specific-endpoint",});const stats = await client.getStats();// {// activeSubscribers: number,// totalSent: number,// totalFailed: number,// monthlySent: number// }エラーハンドリング
Section titled “エラーハンドリング”notify / subscribe / getStats はいずれも、API がエラーレスポンスを返すと PushCFError を throw します。PushCFError は status(HTTP ステータスコード)と code(API のエラーコード文字列。エラーコード一覧を参照)のプロパティを持ちます。
import { PushCF, PushCFError } from "@todoke/sdk";
try { await client.notify({ title: "テスト", body: "送信" });} catch (err) { if (err instanceof PushCFError) { console.error(`[${err.code}] ${err.message} (status: ${err.status})`); }}典型的なエラーコードで処理を分岐する例:
import { PushCF, PushCFError } from "@todoke/sdk";
try { await client.notify({ title: "hi", body: "yo" });} catch (err) { if (err instanceof PushCFError && err.code === "MONTHLY_LIMIT_EXCEEDED") { // 月間上限。翌月まで待つかプランをアップグレード }}type PushCFOptions = { apiKey: string; baseUrl?: string; // 省略時は "https://api.todoke.dev"};
type NotifyPayload = { title: string; body: string; url?: string; // https:// のみ icon?: string; // https:// のみ badge?: string; // https:// のみ endpoint?: string; // 指定時は特定購読者のみ};
type SubscribeOptions = { registration: ServiceWorkerRegistration; // 登録済みの Service Worker};
type Stats = { activeSubscribers: number; totalSent: number; totalFailed: number; monthlySent: number;};