用 Claude Code 加速 Firebase 开发实战指南
结合 Claude Code 与 Firebase(Firestore、Authentication、Cloud Functions)快速开发全栈应用,附完整代码示例。
Firebase 与 Claude Code
Firebase 是 Google 提供的 BaaS 平台。借助 Claude Code,可以把 Firebase 的各项服务整合起来高效开发应用。
Firestore 数据设计
// lib/firebase.ts
import { initializeApp } from "firebase/app";
import { getFirestore, collection, doc } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
});
export const db = getFirestore(app);
export const auth = getAuth(app);
// 类型安全的集合引用
import {
CollectionReference,
DocumentData,
collection as fbCollection,
} from "firebase/firestore";
function typedCollection<T extends DocumentData>(path: string) {
return fbCollection(db, path) as CollectionReference<T>;
}
interface Post {
title: string;
content: string;
authorId: string;
authorName: string;
published: boolean;
tags: string[];
createdAt: Date;
updatedAt: Date;
}
export const postsRef = typedCollection<Post>("posts");
CRUD 操作
import {
addDoc,
updateDoc,
deleteDoc,
doc,
getDoc,
getDocs,
query,
where,
orderBy,
limit,
startAfter,
serverTimestamp,
DocumentSnapshot,
} from "firebase/firestore";
// 创建
async function createPost(data: Omit<Post, "createdAt" | "updatedAt">) {
const docRef = await addDoc(postsRef, {
...data,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
});
return docRef.id;
}
// 获取(分页)
async function getPosts(params: {
pageSize?: number;
lastDoc?: DocumentSnapshot;
tag?: string;
}) {
const { pageSize = 20, lastDoc, tag } = params;
const constraints = [
where("published", "==", true),
orderBy("createdAt", "desc"),
limit(pageSize),
];
if (tag) {
constraints.unshift(where("tags", "array-contains", tag));
}
if (lastDoc) {
constraints.push(startAfter(lastDoc));
}
const q = query(postsRef, ...constraints);
const snapshot = await getDocs(q);
return {
posts: snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})),
lastDoc: snapshot.docs[snapshot.docs.length - 1],
hasMore: snapshot.docs.length === pageSize,
};
}
// 更新
async function updatePost(id: string, data: Partial<Post>) {
const ref = doc(postsRef, id);
await updateDoc(ref, {
...data,
updatedAt: serverTimestamp(),
});
}
认证
import {
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
signInWithPopup,
GoogleAuthProvider,
onAuthStateChanged,
User,
} from "firebase/auth";
async function signUp(email: string, password: string, name: string) {
const { user } = await createUserWithEmailAndPassword(
auth,
email,
password
);
// 把用户资料写入 Firestore
await setDoc(doc(db, "users", user.uid), {
email,
name,
createdAt: serverTimestamp(),
});
return user;
}
async function signInWithGoogle() {
const provider = new GoogleAuthProvider();
const { user } = await signInWithPopup(auth, provider);
// 首次登录时创建资料
const userDoc = await getDoc(doc(db, "users", user.uid));
if (!userDoc.exists()) {
await setDoc(doc(db, "users", user.uid), {
email: user.email,
name: user.displayName,
avatar: user.photoURL,
createdAt: serverTimestamp(),
});
}
return user;
}
// React Hook
function useAuth() {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
return onAuthStateChanged(auth, (user) => {
setUser(user);
setLoading(false);
});
}, []);
return { user, loading };
}
Cloud Functions
// functions/src/index.ts
import { onDocumentCreated } from "firebase-functions/v2/firestore";
import { onCall, HttpsError } from "firebase-functions/v2/https";
import { getFirestore } from "firebase-admin/firestore";
import { initializeApp } from "firebase-admin/app";
initializeApp();
const db = getFirestore();
// Firestore 触发器
export const onPostCreated = onDocumentCreated(
"posts/{postId}",
async (event) => {
const post = event.data?.data();
if (!post) return;
// 更新作者的发布计数
const authorRef = db.doc(`users/${post.authorId}`);
await authorRef.update({
postCount: FieldValue.increment(1),
});
// 创建通知
await db.collection("notifications").add({
type: "new_post",
title: `新文章: ${post.title}`,
userId: post.authorId,
createdAt: FieldValue.serverTimestamp(),
read: false,
});
}
);
// Callable Function
export const publishPost = onCall(async (request) => {
if (!request.auth) {
throw new HttpsError("unauthenticated", "Authentication required");
}
const { postId } = request.data;
const postRef = db.doc(`posts/${postId}`);
const post = await postRef.get();
if (!post.exists) {
throw new HttpsError("not-found", "Post not found");
}
if (post.data()?.authorId !== request.auth.uid) {
throw new HttpsError("permission-denied", "Not the author");
}
await postRef.update({
published: true,
publishedAt: FieldValue.serverTimestamp(),
});
return { success: true };
});
安全规则
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId} {
allow read: if resource.data.published == true;
allow create: if request.auth != null
&& request.resource.data.authorId == request.auth.uid;
allow update, delete: if request.auth != null
&& resource.data.authorId == request.auth.uid;
}
match /users/{userId} {
allow read: if true;
allow write: if request.auth != null
&& request.auth.uid == userId;
}
}
}
Claude Code 的实际用法
以下是请 Claude Code 帮忙做 Firebase 开发的示例。和 Supabase 的对比可以看 Supabase 集成开发,认证设计方面请参考 JWT 认证模式。
帮我用 Firebase 做一个聊天应用:
- Google 登录
- 用 Firestore 管理消息
- 实时更新
- 用 Cloud Functions 处理通知
- 配置安全规则
更多信息请参阅 Firebase 官方文档。Claude Code 的使用方法请参阅 官方文档。
总结
Firebase 作为全栈应用的 BaaS 非常强大。借助 Claude Code,把 Firestore、Authentication、Cloud Functions 整合起来实现,可以快速搭建一款产品。
#Claude Code
#Firebase
#Firestore
#Cloud Functions
#BaaS
M
本文作者
Masa
深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。
相关文章
Use Cases
用 Claude Code 加速个人项目开发【附实战案例】
详解如何用 Claude Code 大幅提升个人项目的开发速度。包含从创意到上线的完整实战案例和工作流。
Use Cases
如何用 Claude Code 自动化代码重构
详解如何利用 Claude Code 高效完成代码重构自动化。包含实用提示词和真实项目中的重构模式。
Use Cases
Complete CORS Configuration Guide:Claude Code 实战指南
了解complete cors configuration guide:Claude Code 实战. 包含实用技巧和代码示例。