ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
ဒီ lesson က Tutorial ရဲ့ နောက်ပိုင်း chapters ဖြစ်တဲ့ Storage, Query, Security Rules တွေကို တစ်ခုချင်းစီ သီးခြားမလေ့ကျင့်တော့ဘဲ features အားလုံးကို ပေါင်းစပ်ပြီး real app flow တစ်ခုအနေနဲ့ လေ့ကျင့်ပေးပါတယ်။ File တစ်ခု upload လုပ်ပြီးရင် Storage URL ကို Firestore document ထဲမှာ ပြန်သိမ်းတတ်ဖို့နဲ့ query with where/orderBy တွေကို ပေါင်းသုံးတတ်ဖို့ ဒီအဆင့်မှာ အရေးကြီးပါတယ်။ ပထမ lesson ထက် ပိုခက်တဲ့အကြောင်းက data flow တစ်ခုလုံးကို end-to-end ကိုယ်တိုင် design ချရမှာဖြစ်လို့ပါ။ Security Rules ကိုလည်း owner ချင်းသာ edit/delete လုပ်ခွင့်ရအောင် ကန့်သတ်ရေးကျင့်ရပါလိမ့်မယ်။
လေ့ကျင့်ခန်းများ
Task 1 — user profile avatar image ကို Storage ထဲ upload လုပ်ပြီး getDownloadURL နဲ့ ရလာတဲ့ URL ကို users collection ထဲက user document မှာ avatarUrl field အဖြစ် update လုပ်ပါ။ Task 2 — posts collection ဆောက်ပြီး authorId, createdAt field ပါတဲ့ post document အများကြီး add ထားပါ၊ ပြီးရင် where('authorId','==',uid) နဲ့ orderBy('createdAt','desc') ပေါင်းသုံးထားတဲ့ query တစ်ခု ရေးပါ။ Task 3 — post document ကို post owner ကသာ update/delete လုပ်ခွင့်ရအောင် Firestore Security Rules ရေးပါ၊ owner မဟုတ်သူ edit ကြိုးစားရင် permission-denied error ပြန်ရအောင် စစ်ကြည့်ပါ။ Task 4 (Bonus) — image size 2MB ထက်ကြီးရင် upload မခံအောင် Storage Rules ထဲမှာ request.resource.size နဲ့ ကန့်သတ်ချက် ထည့်ကြည့်ပါ။
Code နမူနာ
// Task skeleton — ကိုယ်တိုင်ဖြည့်စွက်ရန်
import { storage, db } from "./firebase-config";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
import {
collection,
doc,
updateDoc,
query,
where,
orderBy,
getDocs,
} from "firebase/firestore";
// Task 1: Avatar upload
async function uploadAvatar(uid, file) {
const avatarRef = ref(storage, `avatars/${uid}.jpg`);
await uploadBytes(avatarRef, file);
const url = await getDownloadURL(avatarRef);
// TODO: users/{uid} document ထဲ avatarUrl update လုပ်ပါ
}
// Task 2: Compound query
async function getMyPosts(uid) {
const q = query(
collection(db, "posts"),
where("authorId", "==", uid),
orderBy("createdAt", "desc")
);
const snap = await getDocs(q);
return snap.docs.map((d) => ({ id: d.id, ...d.data() }));
}
// Task 3: Security Rules (firestore.rules ဖိုင်ထဲရေးရန်)
// match /posts/{postId} {
// allow update, delete: if request.auth.uid == resource.data.authorId;
// }Avatar image upload ဖြစ်ပြီး profile ပေါ်မှာ ပြသနိုင်ပါလိမ့်မယ်၊ user ကိုယ်ပိုင် post တွေကိုသာ sort ဖြစ်ပြီး query ရလာမယ်၊ post owner မဟုတ်တဲ့သူ edit ကြိုးစားရင် Firestore ကနေ permission-denied error ပြန်ရပါလိမ့်မယ်။၅ မိနစ် စမ်းကြည့်
5 မိနစ်အတွင်း Task 3 ရဲ့ Security Rules တစ်ကြောင်းတည်းကို Firebase Console Rules Playground မှာ owner uid မတူတဲ့ request တစ်ခု simulate လုပ်ပြီး deny ဖြစ်မဖြစ် စမ်းကြည့်ပါ။
သတိလေးတစ်ချက်
Storage Rules ထဲမှာ file size limit ထည့်တာကို လွတ်ထားရင် user က ကြီးမားတဲ့ file တွေ upload လုပ်ပြီး storage cost မမျှော်လင့်ဘဲ မြင့်တက်နိုင်တာကို သတိထားပါ။