Firebase完全ガイド
Firebase完全ガイド
Section titled “Firebase完全ガイド”Firebaseの実践的な実装方法を、実務で使える実装例とベストプラクティスとともに詳しく解説します。
1. Firebaseとは
Section titled “1. Firebaseとは”Firebaseの特徴
Section titled “Firebaseの特徴”Firebaseは、Googleが提供するBaaS(Backend as a Service)プラットフォームです。
Firebaseの主要機能 ├─ Authentication(認証) ├─ Firestore(データベース) ├─ Storage(ストレージ) ├─ Hosting(ホスティング) └─ Cloud Functions(サーバーレス関数)2. 環境構築
Section titled “2. 環境構築”Firebase CLIのインストール
Section titled “Firebase CLIのインストール”# Firebase CLIのインストールnpm install -g firebase-tools
# ログインfirebase login
# プロジェクトの初期化firebase init設定ファイル
Section titled “設定ファイル”{ "firestore": { "rules": "firestore.rules", "indexes": "firestore.indexes.json" }, "hosting": { "public": "public", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "**", "destination": "/index.html" } ] }}3. Authentication(認証)
Section titled “3. Authentication(認証)”// Firebase Authenticationの設定import { initializeApp } from 'firebase/app';import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword } from 'firebase/auth';
const firebaseConfig = { apiKey: "your-api-key", authDomain: "your-project.firebaseapp.com", projectId: "your-project-id"};
const app = initializeApp(firebaseConfig);const auth = getAuth(app);
// ユーザー登録async function signUp(email: string, password: string) { try { const userCredential = await createUserWithEmailAndPassword(auth, email, password); return userCredential.user; } catch (error) { console.error('Sign up error:', error); throw error; }}
// ログインasync function signIn(email: string, password: string) { try { const userCredential = await signInWithEmailAndPassword(auth, email, password); return userCredential.user; } catch (error) { console.error('Sign in error:', error); throw error; }}4. Firestore(データベース)
Section titled “4. Firestore(データベース)”Firestoreの実装
Section titled “Firestoreの実装”import { getFirestore, collection, addDoc, getDocs, doc, updateDoc, deleteDoc } from 'firebase/firestore';
const db = getFirestore(app);
// データの追加async function addUser(userData: { name: string; email: string }) { try { const docRef = await addDoc(collection(db, 'users'), userData); return docRef.id; } catch (error) { console.error('Error adding user:', error); throw error; }}
// データの取得async function getUsers() { try { const querySnapshot = await getDocs(collection(db, 'users')); return querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); } catch (error) { console.error('Error getting users:', error); throw error; }}
// データの更新async function updateUser(userId: string, data: Partial<User>) { try { const userRef = doc(db, 'users', userId); await updateDoc(userRef, data); } catch (error) { console.error('Error updating user:', error); throw error; }}
// データの削除async function deleteUser(userId: string) { try { await deleteDoc(doc(db, 'users', userId)); } catch (error) { console.error('Error deleting user:', error); throw error; }}リアルタイムリスナー
Section titled “リアルタイムリスナー”import { onSnapshot } from 'firebase/firestore';
// リアルタイムでデータを監視function subscribeToUsers(callback: (users: User[]) => void) { const unsubscribe = onSnapshot(collection(db, 'users'), (snapshot) => { const users = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); callback(users); });
return unsubscribe;}5. Storage(ストレージ)
Section titled “5. Storage(ストレージ)”ファイルアップロード
Section titled “ファイルアップロード”import { getStorage, ref, uploadBytes, getDownloadURL } from 'firebase/storage';
const storage = getStorage(app);
// ファイルのアップロードasync function uploadFile(file: File, path: string) { try { const storageRef = ref(storage, path); const snapshot = await uploadBytes(storageRef, file); const downloadURL = await getDownloadURL(snapshot.ref); return downloadURL; } catch (error) { console.error('Error uploading file:', error); throw error; }}6. Cloud Functions
Section titled “6. Cloud Functions”Cloud Functionsの実装
Section titled “Cloud Functionsの実装”import * as functions from 'firebase-functions';import * as admin from 'firebase-admin';
admin.initializeApp();
export const onUserCreate = functions.firestore .document('users/{userId}') .onCreate(async (snap, context) => { const userData = snap.data();
// ユーザー作成時の処理 await admin.firestore().collection('logs').add({ type: 'user_created', userId: context.params.userId, timestamp: admin.firestore.FieldValue.serverTimestamp() });
return null; });7. セキュリティルール
Section titled “7. セキュリティルール”Firestoreセキュリティルール
Section titled “Firestoreセキュリティルール”rules_version = '2';service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read: if request.auth != null && request.auth.uid == userId; allow write: if request.auth != null && request.auth.uid == userId; } }}8. 実践的なベストプラクティス
Section titled “8. 実践的なベストプラクティス”エラーハンドリング
Section titled “エラーハンドリング”async function safeFirestoreOperation<T>( operation: () => Promise<T>): Promise<T | null> { try { return await operation(); } catch (error) { console.error('Firestore operation failed:', error); return null; }}データの構造化
Section titled “データの構造化”// 良い例: 適切なデータ構造interface User { id: string; name: string; email: string; createdAt: Date; updatedAt: Date;}
// 悪い例: ネストが深すぎるinterface BadUser { data: { personal: { info: { name: string; } } }}Firebase完全ガイドのポイント:
- 認証: Authenticationによるユーザー認証
- データベース: Firestoreによるデータ管理
- ストレージ: Storageによるファイル管理
- Cloud Functions: サーバーレス関数
- セキュリティ: セキュリティルールの設定
- ベストプラクティス: エラーハンドリング、データ構造化
適切なFirebaseの使用により、迅速な開発が可能になります。