コンテンツにスキップ

TypeScript SDK

@todoke/sdk を使うと、購読登録から通知送信まで数行で実装できます。

Terminal window
npm install @todoke/sdk
import { PushCF } from "@todoke/sdk";
const client = new PushCF({
apiKey: "pk_your_key",
// baseUrl: "https://api.todoke.dev" // デフォルト値
});

PushCF インスタンスは以下の 3 つのメソッドを提供します。

メソッド説明必要スコープ
notify(payload: NotifyPayload): Promise<void>通知を送信する(POST /api/v1/notifynotify 以上
subscribe({ registration }: SubscribeOptions): Promise<void>ブラウザの Push 購読を登録するsubscribe_only 以上
getStats(): Promise<Stats>統計情報を取得する(GET /api/v1/statsnotify 以上
// Service Worker の準備(事前に /sw.js を配置)
const registration = await navigator.serviceWorker.ready;
// 購読登録(ブラウザ通知許可ダイアログが表示される)
await client.subscribe({ registration });

subscribe は内部で次の 3 段階の処理を順に行います。

  1. GET /api/v1/vapid-public-key を呼び出し、アプリの VAPID 公開鍵を取得する
  2. 取得した鍵を applicationServerKey として registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey }) を呼び出す(ここでブラウザの通知許可ダイアログが表示される)
  3. 作成された購読情報(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
// }

notify / subscribe / getStats はいずれも、API がエラーレスポンスを返すと PushCFError を throw します。PushCFErrorstatus(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;
};