Package Exports
- firebase-rest-firestore
- firebase-rest-firestore/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (firebase-rest-firestore) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Firebase REST Firestore
Firebase Firestore REST API client for Edge runtime environments like Cloudflare Workers and Vercel Edge Functions.
Features
- Works in Edge runtime environments where Firebase Admin SDK is not available
- Full CRUD operations support
- TypeScript support
- Token caching for better performance
- Simple and intuitive API
- Explicit configuration without hidden environment variable dependencies
Installation
npm install firebase-rest-firestoreUsage
Basic usage with explicit configuration
import { createFirestoreClient } from "firebase-rest-firestore";
// Create a client with your configuration
const firestore = createFirestoreClient({
projectId: "your-project-id",
privateKey: "your-private-key",
clientEmail: "your-client-email",
});
// Create a document
const game = await firestore.create("games", {
name: "New Game",
createdAt: new Date(),
score: 100,
active: true,
});
console.log("Created game ID:", game.id);
// Get a document
const fetchedGame = await firestore.get("games", game.id);
console.log("Fetched game:", fetchedGame);
// Update a document
const updatedGame = await firestore.update("games", game.id, {
...fetchedGame,
name: "Updated Game Name",
updatedAt: new Date(),
});
// Query documents
const userGames = await firestore.query("games", {
where: [{ field: "score", op: "GREATER_THAN", value: 50 }],
orderBy: "createdAt",
limit: 10,
});
console.log("Games with score > 50:", userGames);
// Delete a document
await firestore.delete("games", game.id);Configuration
The FirestoreConfig object requires the following properties:
| Property | Description |
|---|---|
| projectId | Firebase project ID |
| privateKey | Service account private key |
| clientEmail | Service account client email |
API Reference
FirestoreClient
The main class for interacting with Firestore.
create(collectionName, data)
Creates a new document in the specified collection.
get(collectionName, documentId)
Retrieves a document by ID.
update(collectionName, documentId, data)
Updates an existing document.
delete(collectionName, documentId)
Deletes a document.
query(collectionName, options)
Queries documents in a collection with filtering, ordering, and pagination.
createFirestoreClient(config)
Creates a new FirestoreClient instance with the provided configuration.
loadConfigFromEnv()
Helper function to load configuration from environment variables.
License
MIT
エラーハンドリング
Firebase REST Firestore は、API リクエスト中にエラーが発生した場合、適切なエラーメッセージを含む例外をスローします。以下はエラーハンドリングの例です:
try {
// ドキュメントの取得を試みる
const game = await firestore.get("games", "non-existent-id");
// ドキュメントが存在しない場合はnullが返される
if (game === null) {
console.log("ドキュメントが見つかりませんでした");
return;
}
// ドキュメントが存在する場合の処理
console.log("取得したゲーム:", game);
} catch (error) {
// API呼び出し中のエラー(認証エラーやネットワークエラーなど)
console.error("Firestoreエラー:", error.message);
}一般的なエラーケース:
- 認証エラー(無効なクレデンシャル)
- ネットワークエラー
- 無効なクエリパラメータ
- Firestore のレート制限
クエリオプションの詳細
queryメソッドでは、以下のオプションを使用して Firestore のドキュメントをフィルタリング、ソート、ページネーションできます:
where
複数のフィルター条件を指定できます。各条件は以下のプロパティを持つオブジェクトです:
field: フィルタリングするフィールド名op: 比較演算子。以下の値が使用可能です:EQUAL: 等しいNOT_EQUAL: 等しくないLESS_THAN: より小さいLESS_THAN_OR_EQUAL: 以下GREATER_THAN: より大きいGREATER_THAN_OR_EQUAL: 以上ARRAY_CONTAINS: 配列に含まれるIN: 指定した値のいずれかに等しいARRAY_CONTAINS_ANY: 配列が指定した値のいずれかを含むNOT_IN: 指定した値のいずれにも等しくない
value: 比較する値
// スコアが50より大きく、activeがtrueのゲームを検索
const games = await firestore.query("games", {
where: [
{ field: "score", op: "GREATER_THAN", value: 50 },
{ field: "active", op: "EQUAL", value: true },
],
});orderBy
結果を並べ替えるフィールド名を指定します。デフォルトでは昇順(ASCENDING)でソートされます。
// 作成日時で並べ替え
const games = await firestore.query("games", {
orderBy: "createdAt",
});limit
返される結果の最大数を指定します。
// 最大10件のドキュメントを取得
const games = await firestore.query("games", {
limit: 10,
});offset
結果のスキップ数を指定します。ページネーションに使用できます。
// 最初の20件をスキップして、次の10件を取得
const games = await firestore.query("games", {
offset: 20,
limit: 10,
});複合クエリの例:
// アクティブなゲームをスコアの高い順に10件取得
const topGames = await firestore.query("games", {
where: [{ field: "active", op: "EQUAL", value: true }],
orderBy: "score", // スコアでソート
limit: 10,
});日本語ドキュメント
概要
Firebase Firestore REST API クライアントは、Cloudflare Workers や Vercel Edge Functions などのエッジランタイム環境向けに設計されています。Firebase Admin SDK が利用できない環境で Firestore を操作するための軽量なライブラリです。
特徴
- エッジランタイム環境での動作(Firebase Admin SDK が利用できない環境)
- 完全な CRUD 操作のサポート
- TypeScript サポート
- パフォーマンス向上のためのトークンキャッシュ
- シンプルで直感的な API
- 環境変数に依存しない明示的な設定
インストール
npm install firebase-rest-firestore基本的な使い方
import { createFirestoreClient } from "firebase-rest-firestore";
// 設定を指定してクライアントを作成
const firestore = createFirestoreClient({
projectId: "あなたのプロジェクトID",
privateKey: "サービスアカウントの秘密鍵",
clientEmail: "サービスアカウントのメールアドレス",
});
// ドキュメントの作成
const game = await firestore.create("games", {
name: "新しいゲーム",
createdAt: new Date(),
score: 100,
active: true,
});
console.log("作成されたゲームID:", game.id);
// ドキュメントの取得
const fetchedGame = await firestore.get("games", game.id);
console.log("取得したゲーム:", fetchedGame);
// ドキュメントの更新
const updatedGame = await firestore.update("games", game.id, {
...fetchedGame,
name: "更新されたゲーム名",
updatedAt: new Date(),
});
// ドキュメントのクエリ
const userGames = await firestore.query("games", {
where: [{ field: "score", op: "GREATER_THAN", value: 50 }],
orderBy: "createdAt",
limit: 10,
});
console.log("スコアが50より大きいゲーム:", userGames);
// ドキュメントの削除
await firestore.delete("games", game.id);制限事項とロードマップ
現在の制限事項
- バッチ操作: 現在のバージョンでは、複数のドキュメントを一度に操作するバッチ処理はサポートされていません。
- トランザクション: 原子的なトランザクション操作はサポートされていません。
- リアルタイムリスナー: REST API の性質上、リアルタイムのデータ同期はサポートされていません。
- サブコレクション: 現在のバージョンでは、ネストされたサブコレクションの直接的なサポートは限定的です。
将来のロードマップ
以下の機能は将来のバージョンで実装予定です:
- バッチ操作のサポート
- 基本的なトランザクションのサポート
- サブコレクションの改善されたサポート
- より詳細なクエリオプション(複合インデックスなど)
- パフォーマンス最適化
機能リクエストやバグ報告は、GitHub の Issue でお知らせください。
エッジランタイムでの使用例
Cloudflare Workers
// wrangler.toml に以下の環境変数を設定してください
// FIREBASE_PROJECT_ID
// FIREBASE_PRIVATE_KEY
// FIREBASE_CLIENT_EMAIL
import { createFirestoreClient } from "firebase-rest-firestore";
export default {
async fetch(request, env, ctx) {
// 環境変数から設定を読み込む
const firestore = createFirestoreClient({
projectId: env.FIREBASE_PROJECT_ID,
privateKey: env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n"),
clientEmail: env.FIREBASE_CLIENT_EMAIL,
});
const url = new URL(request.url);
const path = url.pathname;
// APIエンドポイントの例
if (path === "/api/games" && request.method === "GET") {
try {
// アクティブなゲームを取得
const games = await firestore.query("games", {
where: [{ field: "active", op: "EQUAL", value: true }],
limit: 10,
});
return new Response(JSON.stringify(games), {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
return new Response("Not found", { status: 404 });
},
};Vercel Edge Functions
// .env.local に以下の環境変数を設定してください
// FIREBASE_PROJECT_ID
// FIREBASE_PRIVATE_KEY
// FIREBASE_CLIENT_EMAIL
import { createFirestoreClient } from "firebase-rest-firestore";
export const config = {
runtime: "edge",
};
export default async function handler(request) {
// 環境変数から設定を読み込む
const firestore = createFirestoreClient({
projectId: process.env.FIREBASE_PROJECT_ID,
privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, "\n"),
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
});
try {
// 最新の10件のドキュメントを取得
const documents = await firestore.query("posts", {
orderBy: "createdAt",
limit: 10,
});
return new Response(JSON.stringify(documents), {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}パフォーマンスに関する注意点
トークンキャッシュ
Firebase REST Firestore は、パフォーマンスを向上させるために JWT トークンをキャッシュします。デフォルトでは、トークンは 50 分間キャッシュされます(実際のトークン有効期限は 1 時間)。これにより、リクエストごとに新しいトークンを生成する必要がなくなり、API リクエストの速度が向上します。
// トークンは内部的にキャッシュされるため、
// 複数のリクエストでも認証のオーバーヘッドは最小限に抑えられます
const doc1 = await firestore.get("collection", "doc1");
const doc2 = await firestore.get("collection", "doc2");
const doc3 = await firestore.get("collection", "doc3");クエリの最適化
大量のデータを扱う場合は、以下の点に注意してください:
適切な制限を設定する: 常に
limitパラメータを使用して、返されるドキュメント数を制限してください。必要なフィールドのみをクエリする: 将来のバージョンでは、特定のフィールドのみを取得する機能が追加される予定です。
インデックスの作成: 複雑なクエリを実行する場合は、Firebase コンソールで適切なインデックスを作成してください。
ページネーションの使用: 大量のデータを取得する場合は、
offsetとlimitを組み合わせてページネーションを実装してください。
エッジ環境での注意点
エッジ環境では、以下の点に注意してください:
コールドスタート: 初回実行時にはトークン生成のオーバーヘッドがあります。
メモリ使用量: 大量のデータを一度に処理する場合は、メモリ制限に注意してください。
タイムアウト: 長時間実行されるクエリは、エッジ環境のタイムアウト制限に達する可能性があります。