把 Firebase 的几块主能力串起来,你会看到它为什么对小团队很有吸引力。
#场景:开一个“云端店铺后台”
需求:
- 用户 Google 登录
- 商品列表放 Firestore
- 商品图片放 Storage
- 新商品发布时用 Functions 记日志
- 管理台页面部署到 Hosting
- 断网时仍能看最近数据
#前端初始化
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider, signInWithPopup } from "firebase/auth";
import {
initializeFirestore,
persistentLocalCache,
persistentSingleTabManager,
collection,
addDoc,
onSnapshot
} from "firebase/firestore";
import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage";
const firebaseConfig = {
apiKey: "xxx",
authDomain: "xxx.firebaseapp.com",
projectId: "xxx",
storageBucket: "xxx.firebasestorage.app",
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const provider = new GoogleAuthProvider();
const db = initializeFirestore(app, {
localCache: persistentLocalCache({
tabManager: persistentSingleTabManager()
})
});
const storage = getStorage(app);
export async function login() {
await signInWithPopup(auth, provider);
}
export async function createProduct(input: {
name: string;
price: number;
image: File;
}) {
const imageRef = ref(storage, `products/${Date.now()}-${input.image.name}`);
await uploadBytes(imageRef, input.image);
const imageUrl = await getDownloadURL(imageRef);
await addDoc(collection(db, "products"), {
name: input.name,
price: input.price,
imageUrl,
createdAt: new Date(),
});
}
export function watchProducts(callback: (items: any[]) => void) {
return onSnapshot(collection(db, "products"), (snapshot) => {
callback(
snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}))
);
});
}#服务端事件后处理
import { onDocumentCreated } from "firebase-functions/v2/firestore";
export const onProductCreated = onDocumentCreated(
"products/{productId}",
async (event) => {
const data = event.data?.data();
console.log("新商品创建:", data?.name);
}
);#整体业务图
管理员登录
↓
Auth 发门禁凭证
↓
上传图片到 Storage 云仓库
↓
商品记录写入 Firestore 主账本
↓
前台列表通过 onSnapshot 实时刷新
↓
Functions 收到账本事件做后处理
↓
整个管理台由 Hosting 对外提供这就是 Firebase 的精髓:
很多业务不是“前端 + 单独后端 + 单独对象存储 + 单独鉴权 + 单独部署”五件套,而是同一商圈里几套物业服务直接联动。