1. शुरू करने से पहले
क्लाउड फायरस्टोर और क्लाउड फ़ंक्शंस जैसे सर्वर रहित बैकएंड टूल का उपयोग करना बहुत आसान है, लेकिन परीक्षण करना कठिन हो सकता है। फायरबेस लोकल एमुलेटर सूट आपको इन सेवाओं के स्थानीय संस्करणों को अपनी विकास मशीन पर चलाने की अनुमति देता है ताकि आप अपना ऐप जल्दी और सुरक्षित रूप से विकसित कर सकें।
आवश्यक शर्तें
- एक साधारण संपादक जैसे विजुअल स्टूडियो कोड, एटम, या सबलाइम टेक्स्ट
- Node.js 10.0.0 या उच्चतर (Node.js स्थापित करने के लिए, nvm का उपयोग करें , अपने संस्करण की जांच करने के लिए,
node --version
चलाएँ) - जावा 7 या उच्चतर (जावा स्थापित करने के लिए इन निर्देशों का उपयोग करें , अपने संस्करण की जांच करने के लिए,
java -version
चलाएं)
आप क्या करेंगे
इस कोडलैब में, आप एक साधारण ऑनलाइन शॉपिंग ऐप चलाएंगे और डिबग करेंगे जो कई फायरबेस सेवाओं द्वारा संचालित है:
- Cloud Firestore: रीयल-टाइम क्षमताओं के साथ विश्व स्तर पर स्केलेबल, सर्वर रहित, NoSQL डेटाबेस।
- क्लाउड फ़ंक्शंस : एक सर्वर रहित बैकएंड कोड जो घटनाओं या HTTP अनुरोधों के जवाब में चलता है।
- फायरबेस प्रमाणीकरण : एक प्रबंधित प्रमाणीकरण सेवा जो अन्य फायरबेस उत्पादों के साथ एकीकृत होती है।
- फायरबेस होस्टिंग : वेब ऐप्स के लिए तेज और सुरक्षित होस्टिंग।
स्थानीय विकास को सक्षम करने के लिए आप ऐप को एमुलेटर सूट से कनेक्ट करेंगे।
आप यह भी सीखेंगे कि कैसे:
- अपने ऐप को एमुलेटर सूट से कैसे कनेक्ट करें और विभिन्न एमुलेटर कैसे जुड़े हैं।
- फायरबेस सुरक्षा नियम कैसे काम करते हैं और स्थानीय एमुलेटर के खिलाफ फायरस्टोर सुरक्षा नियमों का परीक्षण कैसे करें।
- एक फायरबेस फ़ंक्शन कैसे लिखें जो फायरस्टोर घटनाओं से ट्रिगर होता है और एमुलेटर सूट के खिलाफ चलने वाले एकीकरण परीक्षण कैसे लिखें।
2. सेट अप
स्रोत कोड प्राप्त करें
इस कोडलैब में, आप फायर स्टोर के नमूने के एक संस्करण के साथ शुरुआत करते हैं जो लगभग पूरा हो चुका है, इसलिए सबसे पहले आपको जो करना है वह है स्रोत कोड का क्लोन बनाना:
$ git clone https://github.com/firebase/emulators-codelab.git
फिर कोडलैब निर्देशिका में जाएँ, जहाँ आप इस कोडलैब के शेष भाग के लिए काम करेंगे:
$ cd emulators-codelab/codelab-initial-state
अब, निर्भरताएँ स्थापित करें ताकि आप कोड चला सकें। यदि आप धीमे इंटरनेट कनेक्शन पर हैं तो इसमें एक या दो मिनट लग सकते हैं:
# Move into the functions directory
$ cd functions
# Install dependencies
$ npm install
# Move back into the previous directory
$ cd ../
फायरबेस सीएलआई प्राप्त करें
एमुलेटर सूट फायरबेस सीएलआई (कमांड-लाइन इंटरफेस) का हिस्सा है जिसे आपकी मशीन पर निम्नलिखित कमांड के साथ स्थापित किया जा सकता है:
$ npm install -g firebase-tools
इसके बाद, पुष्टि करें कि आपके पास CLI का नवीनतम संस्करण है। इस कोडलैब को संस्करण 9.0.0 या उच्चतर संस्करण के साथ काम करना चाहिए लेकिन बाद के संस्करणों में अधिक बग फिक्स शामिल हैं।
$ firebase --version 9.6.0
अपने Firebase प्रोजेक्ट से कनेक्ट करें
अगर आपके पास Firebase प्रोजेक्ट नहीं है, तो Firebase कंसोल में एक नया Firebase प्रोजेक्ट बनाएं. आपके द्वारा चुने गए प्रोजेक्ट आईडी को नोट कर लें, बाद में आपको इसकी आवश्यकता होगी।
अब हमें इस कोड को आपके Firebase प्रोजेक्ट से कनेक्ट करना होगा। फायरबेस सीएलआई में लॉग इन करने के लिए पहले निम्नलिखित कमांड चलाएँ:
$ firebase login
प्रोजेक्ट उपनाम बनाने के लिए अगला निम्न आदेश चलाएं। $YOUR_PROJECT_ID
को अपने Firebase प्रोजेक्ट की आईडी से बदलें।
$ firebase use $YOUR_PROJECT_ID
अब आप ऐप चलाने के लिए तैयार हैं!
3. एमुलेटर चलाएं
इस सेक्शन में, आप ऐप को स्थानीय रूप से चलाएंगे। इसका मतलब है कि एमुलेटर सूट को बूट करने का समय आ गया है।
एमुलेटर शुरू करें
कोडलैब स्रोत निर्देशिका के अंदर से, एमुलेटर शुरू करने के लिए निम्न कमांड चलाएँ:
$ firebase emulators:start --import=./seed
आपको कुछ आउटपुट इस तरह देखना चाहिए:
$ firebase emulators:start --import=./seed i emulators: Starting emulators: auth, functions, firestore, hosting ⚠ functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: database, pubsub i firestore: Importing data from /Users/samstern/Projects/emulators-codelab/codelab-initial-state/seed/firestore_export/firestore_export.overall_export_metadata i firestore: Firestore Emulator logging to firestore-debug.log i hosting: Serving hosting files from: public ✔ hosting: Local server: http://localhost:5000 i ui: Emulator UI logging to ui-debug.log i functions: Watching "/Users/samstern/Projects/emulators-codelab/codelab-initial-state/functions" for Cloud Functions... ✔ functions[calculateCart]: firestore function initialized. ┌─────────────────────────────────────────────────────────────┐ │ ✔ All emulators ready! It is now safe to connect your app. │ │ i View Emulator UI at http://localhost:4000 │ └─────────────────────────────────────────────────────────────┘ ┌────────────────┬────────────────┬─────────────────────────────────┐ │ Emulator │ Host:Port │ View in Emulator UI │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Authentication │ localhost:9099 │ http://localhost:4000/auth │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Functions │ localhost:5001 │ http://localhost:4000/functions │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Firestore │ localhost:8080 │ http://localhost:4000/firestore │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Hosting │ localhost:5000 │ n/a │ └────────────────┴────────────────┴─────────────────────────────────┘ Emulator Hub running at localhost:4400 Other reserved ports: 4500 Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.
एक बार जब आप सभी एमुलेटर शुरू संदेश देखते हैं, तो ऐप उपयोग के लिए तैयार है।
वेब ऐप को एमुलेटर से कनेक्ट करें
लॉग में तालिका के आधार पर हम देख सकते हैं कि क्लाउड फायरस्टोर एमुलेटर पोर्ट 8080
पर सुन रहा है और प्रमाणीकरण एमुलेटर पोर्ट 9099
पर सुन रहा है।
┌────────────────┬────────────────┬─────────────────────────────────┐ │ Emulator │ Host:Port │ View in Emulator UI │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Authentication │ localhost:9099 │ http://localhost:4000/auth │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Functions │ localhost:5001 │ http://localhost:4000/functions │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Firestore │ localhost:8080 │ http://localhost:4000/firestore │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Hosting │ localhost:5000 │ n/a │ └────────────────┴────────────────┴─────────────────────────────────┘
आइए अपने फ्रंटएंड कोड को उत्पादन के बजाय एमुलेटर से कनेक्ट करें। public/js/homepage.js
फ़ाइल खोलें और onDocumentReady
फ़ंक्शन ढूंढें। हम देख सकते हैं कि कोड मानक फायरस्टोर और प्रामाणिक उदाहरणों तक पहुंचता है:
सार्वजनिक/जेएस/होमपेज.जेएस
const auth = firebaseApp.auth();
const db = firebaseApp.firestore();
आइए स्थानीय एमुलेटर को इंगित करने के लिए db
और auth
ऑब्जेक्ट्स को अपडेट करें:
सार्वजनिक/जेएस/होमपेज.जेएस
const auth = firebaseApp.auth();
const db = firebaseApp.firestore();
// ADD THESE LINES
if (location.hostname === "localhost") {
console.log("localhost detected!");
auth.useEmulator("http://localhost:9099");
db.useEmulator("localhost", 8080);
}
अब जब ऐप लोकलहोस्ट (होस्टिंग एमुलेटर द्वारा सेवित) पर चल रहा है, तो फायरस्टोर क्लाइंट प्रोडक्शन डेटाबेस के बजाय स्थानीय एमुलेटर पर भी इशारा करता है।
एमुलेटरयूआई खोलें
अपने वेब ब्राउज़र में, http://localhost:4000/ पर नेविगेट करें। आपको एमुलेटर सूट यूआई देखना चाहिए।
फायरस्टोर एमुलेटर के लिए यूआई देखने के लिए क्लिक करें। --import
ध्वज के साथ आयात किए गए डेटा के कारण items
संग्रह में पहले से ही डेटा है।
4. ऐप चलाएं
ऐप खोलें
अपने वेब ब्राउज़र में, http://localhost:5000 पर नेविगेट करें और आपको अपनी मशीन पर स्थानीय रूप से चल रहे फायर स्टोर को देखना चाहिए!
ऐप का इस्तेमाल करें
होमपेज पर एक आइटम चुनें और कार्ट में जोड़ें पर क्लिक करें। दुर्भाग्य से, आप निम्न त्रुटि का सामना करेंगे:
आइए उस बग को ठीक करें! क्योंकि एमुलेटर में सब कुछ चल रहा है, हम प्रयोग कर सकते हैं और वास्तविक डेटा को प्रभावित करने की चिंता नहीं कर सकते।
5. ऐप को डिबग करें
बग का पता लगाएं
ठीक है, आइए क्रोम डेवलपर कंसोल में देखें। कंसोल पर त्रुटि देखने के लिए Control+Shift+J
(Windows, Linux, Chrome OS) या Command+Option+J
(Mac) दबाएं:
ऐसा लगता है कि addToCart
विधि में कुछ त्रुटि थी, आइए उस पर एक नज़र डालते हैं। हम उस विधि में uid
नामक किसी चीज़ तक पहुँचने का प्रयास कहाँ करते हैं और यह null
क्यों होगा? अभी यह विधि public/js/homepage.js
में इस तरह दिखती है:
सार्वजनिक/जेएस/होमपेज.जेएस
addToCart(id, itemData) {
console.log("addToCart", id, JSON.stringify(itemData));
return this.db
.collection("carts")
.doc(this.auth.currentUser.uid)
.collection("items")
.doc(id)
.set(itemData);
}
आह! हम ऐप में साइन इन नहीं हैं। फायरबेस ऑथेंटिकेशन डॉक्स के अनुसार, जब हम साइन इन नहीं होते हैं, तो auth.currentUser
null
होता है। आइए उसके लिए एक चेक जोड़ें:
सार्वजनिक/जेएस/होमपेज.जेएस
addToCart(id, itemData) {
// ADD THESE LINES
if (this.auth.currentUser === null) {
this.showError("You must be signed in!");
return;
}
// ...
}
ऐप का परीक्षण करें
अब, पेज को रिफ्रेश करें और फिर Add to Cart पर क्लिक करें। आपको इस बार एक अच्छी त्रुटि मिलनी चाहिए:
लेकिन अगर आप ऊपरी टूलबार में साइन इन पर क्लिक करते हैं और फिर कार्ट में जोड़ें पर क्लिक करते हैं, तो आप देखेंगे कि कार्ट अपडेट हो गया है।
हालाँकि, ऐसा नहीं लगता कि संख्याएँ बिल्कुल भी सही हैं:
चिंता न करें, हम जल्द ही उस बग को ठीक कर देंगे। सबसे पहले, आइए गहराई से जानें कि जब आपने अपने कार्ट में कोई आइटम जोड़ा तो वास्तव में क्या हुआ।
6. स्थानीय कार्य ट्रिगर
कार्ट में जोड़ें पर क्लिक करने से घटनाओं की एक श्रृंखला शुरू हो जाती है जिसमें कई एमुलेटर शामिल होते हैं। अपने कार्ट में कोई आइटम जोड़ने के बाद, Firebase CLI लॉग में, आपको निम्न संदेशों जैसा कुछ दिखाई देना चाहिए:
i functions: Beginning execution of "calculateCart" i functions: Finished "calculateCart" in ~1s
उन लॉग और आपके द्वारा देखे गए UI अपडेट को उत्पन्न करने के लिए चार प्रमुख घटनाएं हुईं:
1) फायरस्टोर लिखें - क्लाइंट
Firestore संग्रह /carts/{cartId}/items/{itemId}/
में एक नया दस्तावेज़ जोड़ा गया है। आप इस कोड को addToCart
फ़ंक्शन में public/js/homepage.js
के अंदर देख सकते हैं:
सार्वजनिक/जेएस/होमपेज.जेएस
addToCart(id, itemData) {
// ...
console.log("addToCart", id, JSON.stringify(itemData));
return this.db
.collection("carts")
.doc(this.auth.currentUser.uid)
.collection("items")
.doc(id)
.set(itemData);
}
2) क्लाउड फंक्शन ट्रिगर किया गया
क्लाउड फ़ंक्शन calculateCart
onWrite
ट्रिगर का उपयोग करके कार्ट आइटम के साथ होने वाले किसी भी लेखन ईवेंट (बनाने, अपडेट करने या हटाने) के लिए सुनता है, जिसे आप functions/index.js
इंडेक्स.जेएस में देख सकते हैं:
फ़ंक्शन/index.js
exports.calculateCart = functions.firestore
.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
try {
let totalPrice = 125.98;
let itemCount = 8;
const cartRef = db.collection("carts").doc(context.params.cartId);
await cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
}
);
3) फायरस्टोर लिखें - व्यवस्थापक
calculateCart
फ़ंक्शन कार्ट में सभी आइटम पढ़ता है और कुल मात्रा और मूल्य जोड़ता है, फिर यह "कार्ट" दस्तावेज़ को नए योगों के साथ अपडेट करता है (ऊपर cartRef.update(...)
देखें)।
4) फायरस्टोर रीड - क्लाइंट
कार्ट में परिवर्तनों के बारे में अपडेट प्राप्त करने के लिए वेब फ्रंटएंड की सदस्यता ली गई है। क्लाउड फ़ंक्शन द्वारा नए योग लिखने और UI को अपडेट करने के बाद इसे रीयल-टाइम अपडेट मिलता है, जैसा कि आप public/js/homepage.js
में देख सकते हैं:
सार्वजनिक/जेएस/होमपेज.जेएस
this.cartUnsub = cartRef.onSnapshot(cart => {
// The cart document was changed, update the UI
// ...
});
संक्षिप्त
अच्छा काम! आपने अभी पूरी तरह से स्थानीय ऐप सेट किया है जो पूरी तरह से स्थानीय परीक्षण के लिए तीन अलग-अलग फ़ायरबेस अनुकरणकर्ताओं का उपयोग करता है।
लेकिन रुकिए, और भी बहुत कुछ है! अगले भाग में आप सीखेंगे:
- फायरबेस एमुलेटर का उपयोग करने वाले यूनिट टेस्ट कैसे लिखें।
- अपने सुरक्षा नियमों को डीबग करने के लिए फायरबेस एमुलेटर का उपयोग कैसे करें।
7. आपके ऐप के लिए तैयार किए गए सुरक्षा नियम बनाएं
हमारा वेब ऐप डेटा पढ़ता और लिखता है लेकिन अभी तक हमने सुरक्षा के बारे में बिल्कुल भी चिंता नहीं की है। क्लाउड फायरस्टोर यह घोषित करने के लिए "सुरक्षा नियम" नामक एक प्रणाली का उपयोग करता है कि किसके पास डेटा पढ़ने और लिखने की पहुंच है। एमुलेटर सूट इन नियमों को प्रोटोटाइप करने का एक शानदार तरीका है।
संपादक में, फ़ाइल emulators-codelab/codelab-initial-state/firestore.rules
। आप देखेंगे कि हमारे नियमों में हमारे तीन मुख्य खंड हैं:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// User's cart metadata
match /carts/{cartID} {
// TODO: Change these! Anyone can read or write.
allow read, write: if true;
}
// Items inside the user's cart
match /carts/{cartID}/items/{itemID} {
// TODO: Change these! Anyone can read or write.
allow read, write: if true;
}
// All items available in the store. Users can read
// items but never write them.
match /items/{itemID} {
allow read: if true;
}
}
}
अभी कोई भी हमारे डेटाबेस में डेटा पढ़ और लिख सकता है! हम यह सुनिश्चित करना चाहते हैं कि केवल वैध संचालन ही हो और हम कोई संवेदनशील जानकारी लीक न करें।
इस कोडलैब के दौरान, कम से कम विशेषाधिकार के सिद्धांत का पालन करते हुए, हम सभी दस्तावेज़ों को लॉक कर देंगे और धीरे-धीरे एक्सेस जोड़ देंगे जब तक कि सभी उपयोगकर्ताओं के पास उनकी ज़रूरत की सभी एक्सेस न हो, लेकिन अधिक नहीं। आइए स्थिति को false
पर सेट करके पहुंच से इनकार करने के लिए पहले दो नियमों को अपडेट करें:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// User's cart metadata
match /carts/{cartID} {
// UPDATE THIS LINE
allow read, write: if false;
}
// Items inside the user's cart
match /carts/{cartID}/items/{itemID} {
// UPDATE THIS LINE
allow read, write: if false;
}
// All items available in the store. Users can read
// items but never write them.
match /items/{itemID} {
allow read: if true;
}
}
}
8. एमुलेटर और टेस्ट चलाएं
एमुलेटर शुरू करें
कमांड लाइन पर, सुनिश्चित करें कि आप emulators-codelab/codelab-initial-state/
में हैं। आपके पास अभी भी पिछले चरणों से चल रहे एमुलेटर हो सकते हैं। यदि नहीं, तो एमुलेटर फिर से शुरू करें:
$ firebase emulators:start --import=./seed
एक बार एमुलेटर चलने के बाद, आप उनके खिलाफ स्थानीय रूप से परीक्षण चला सकते हैं।
परीक्षण चलाएं
निर्देशिका से एक नए टर्मिनल टैब में emulators-codelab/codelab-initial-state/
लाइन पर
सबसे पहले फंक्शन्स डायरेक्टरी में जाएँ (हम शेष कोडलैब के लिए यहाँ रहेंगे):
$ cd functions
अब फ़ंक्शन निर्देशिका में मोचा परीक्षण चलाएँ, और आउटपुट के शीर्ष पर स्क्रॉल करें:
# Run the tests $ npm test > functions@ test .../emulators-codelab/codelab-initial-state/functions > mocha shopping carts 1) can be created and updated by the cart owner 2) can be read only by the cart owner shopping cart items 3) can be read only by the cart owner 4) can be added only by the cart owner adding an item to the cart recalculates the cart total. - should sum the cost of their items 0 passing (364ms) 1 pending 4 failing
अभी हमारे पास चार विफलताएं हैं। जैसे ही आप नियम फ़ाइल बनाते हैं, आप अधिक परीक्षण पास देखकर प्रगति को माप सकते हैं।
9. सुरक्षित कार्ट एक्सेस
पहली दो विफलताएं "शॉपिंग कार्ट" परीक्षण हैं जो परीक्षण करती हैं कि:
- उपयोगकर्ता केवल अपनी कार्ट बना और अपडेट कर सकते हैं
- उपयोगकर्ता केवल अपनी कार्ट पढ़ सकते हैं
फंक्शन/टेस्ट.जेएस
it('can be created and updated by the cart owner', async () => {
// Alice can create her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").set({
ownerUID: "alice",
total: 0
}));
// Bob can't create Alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart").set({
ownerUID: "alice",
total: 0
}));
// Alice can update her own cart with a new total
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").update({
total: 1
}));
// Bob can't update Alice's cart with a new total
await firebase.assertFails(bobDb.doc("carts/alicesCart").update({
total: 1
}));
});
it("can be read only by the cart owner", async () => {
// Setup: Create Alice's cart as admin
await admin.doc("carts/alicesCart").set({
ownerUID: "alice",
total: 0
});
// Alice can read her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart").get());
// Bob can't read Alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart").get());
});
आइए इन परीक्षणों को पास करें। संपादक में, सुरक्षा नियम फ़ाइल, firestore.rules
खोलें, और match /carts/{cartID}
के भीतर कथनों को अपडेट करें:
आग की दुकान.नियम
rules_version = '2';
service cloud.firestore {
// UPDATE THESE LINES
match /carts/{cartID} {
allow create: if request.auth.uid == request.resource.data.ownerUID;
allow read, update, delete: if request.auth.uid == resource.data.ownerUID;
}
// ...
}
}
ये नियम अब केवल कार्ट मालिक को पढ़ने और लिखने की अनुमति देते हैं।
आने वाले डेटा और उपयोगकर्ता के प्रमाणीकरण को सत्यापित करने के लिए, हम दो वस्तुओं का उपयोग करते हैं जो प्रत्येक नियम के संदर्भ में उपलब्ध हैं:
-
request
ऑब्जेक्ट में उस ऑपरेशन के बारे में डेटा और मेटाडेटा होता है जिसका प्रयास किया जा रहा है। - अगर कोई Firebase प्रोजेक्ट Firebase प्रमाणीकरण का उपयोग कर रहा है, तो
request.auth
ऑब्जेक्ट उस उपयोगकर्ता का वर्णन करता है जो अनुरोध कर रहा है।
10. टेस्ट कार्ट एक्सेस
जब भी firestore.rules
सहेजा जाता है, तो Emulator Suite स्वचालित रूप से नियमों को अपडेट कर देता है। आप इस बात की पुष्टि कर सकते हैं कि संदेश के लिए एमुलेटर चलाने वाले टैब में देखकर एमुलेटर ने नियमों को अपडेट कर दिया है Rules updated
:
परीक्षणों को फिर से चलाएँ, और जाँचें कि पहले दो परीक्षण अब पास हो गए हैं:
$ npm test > functions@ test .../emulators-codelab/codelab-initial-state/functions > mocha shopping carts ✓ can be created and updated by the cart owner (195ms) ✓ can be read only by the cart owner (136ms) shopping cart items 1) can be read only by the cart owner 2) can be added only by the cart owner adding an item to the cart recalculates the cart total. - should sum the cost of their items 2 passing (482ms) 1 pending 2 failing
अच्छी नौकरी! अब आपने शॉपिंग कार्ट तक पहुंच सुरक्षित कर ली है। आइए अगले असफल परीक्षण पर चलते हैं।
11. UI में "कार्ट में जोड़ें" प्रवाह की जांच करें
अभी, हालांकि कार्ट के मालिक अपनी कार्ट में पढ़ते और लिखते हैं, वे अपनी कार्ट में अलग-अलग आइटम नहीं पढ़ या लिख सकते हैं। ऐसा इसलिए है क्योंकि मालिकों के पास कार्ट दस्तावेज़ तक पहुंच होती है, लेकिन उनके पास कार्ट के आइटम उप- संग्रह तक पहुंच नहीं होती है।
यह उपयोगकर्ताओं के लिए एक टूटी हुई स्थिति है।
वेब UI पर लौटें, जो http://localhost:5000,
और अपने कार्ट में कुछ जोड़ने का प्रयास करें। आपको डिबग कंसोल से दिखाई देने वाली Permission Denied
त्रुटि मिलती है, क्योंकि हमने अभी तक उपयोगकर्ताओं को items
उपसंग्रह में बनाए गए दस्तावेज़ों तक पहुंच प्रदान नहीं की है।
12. कार्ट आइटम को एक्सेस करने दें
ये दो परीक्षण पुष्टि करते हैं कि उपयोगकर्ता केवल अपनी कार्ट में आइटम जोड़ सकते हैं या आइटम पढ़ सकते हैं:
it("can be read only by the cart owner", async () => {
// Alice can read items in her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart/items/milk").get());
// Bob can't read items in alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart/items/milk").get())
});
it("can be added only by the cart owner", async () => {
// Alice can add an item to her own cart
await firebase.assertSucceeds(aliceDb.doc("carts/alicesCart/items/lemon").set({
name: "lemon",
price: 0.99
}));
// Bob can't add an item to alice's cart
await firebase.assertFails(bobDb.doc("carts/alicesCart/items/lemon").set({
name: "lemon",
price: 0.99
}));
});
तो हम एक नियम लिख सकते हैं जो एक्सेस की अनुमति देता है यदि वर्तमान उपयोगकर्ता के पास कार्ट दस्तावेज़ पर मालिक के समान यूआईडी है। चूंकि create, update, delete
के लिए अलग-अलग नियम निर्दिष्ट करने की कोई आवश्यकता नहीं है, आप एक write
नियम का उपयोग कर सकते हैं, जो डेटा को संशोधित करने वाले सभी अनुरोधों पर लागू होता है।
आइटम उपसंग्रह में दस्तावेज़ों के लिए नियम अपडेट करें। सशर्त में get
करें फायरस्टोर से एक मूल्य पढ़ रहा है-इस मामले में, कार्ट दस्तावेज़ पर ownerUID
।
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// ...
// UPDATE THESE LINES
match /carts/{cartID}/items/{itemID} {
allow read, write: if get(/databases/$(database)/documents/carts/$(cartID)).data.ownerUID == request.auth.uid;
}
// ...
}
}
13. टेस्ट कार्ट आइटम एक्सेस
अब हम परीक्षण फिर से चला सकते हैं। आउटपुट के शीर्ष पर स्क्रॉल करें और जांचें कि अधिक परीक्षण पास होते हैं:
$ npm test > functions@ test .../emulators-codelab/codelab-initial-state/functions > mocha shopping carts ✓ can be created and updated by the cart owner (195ms) ✓ can be read only by the cart owner (136ms) shopping cart items ✓ can be read only by the cart owner (111ms) ✓ can be added only by the cart owner adding an item to the cart recalculates the cart total. - should sum the cost of their items 4 passing (401ms) 1 pending
अच्छा! अब हमारे सभी परीक्षण पास हो गए हैं। हमारे पास एक लंबित परीक्षण है, लेकिन हम कुछ चरणों में उस तक पहुंच जाएंगे।
14. "कार्ट में जोड़ें" प्रवाह को फिर से जांचें
वेब फ्रंट एंड पर लौटें ( http://localhost:5000 ) और कार्ट में एक आइटम जोड़ें। यह पुष्टि करने के लिए एक महत्वपूर्ण कदम है कि हमारे परीक्षण और नियम क्लाइंट द्वारा आवश्यक कार्यक्षमता से मेल खाते हैं। (याद रखें कि पिछली बार जब हमने UI को आज़माया था तो उपयोगकर्ता अपने कार्ट में आइटम नहीं जोड़ पाए थे!)
जब firestore.rules
सहेजा जाता है, तो क्लाइंट स्वचालित रूप से नियमों को पुनः लोड करता है। तो, कार्ट में कुछ जोड़ने का प्रयास करें।
संक्षिप्त
अच्छा काम! आपने अभी-अभी अपने ऐप की सुरक्षा में सुधार किया है, जो इसे उत्पादन के लिए तैयार करने के लिए एक आवश्यक कदम है! यदि यह एक प्रोडक्शन ऐप होता, तो हम इन परीक्षणों को अपनी निरंतर एकीकरण पाइपलाइन में जोड़ सकते थे। यह हमें आगे जाकर विश्वास दिलाएगा कि हमारे शॉपिंग कार्ट डेटा में ये एक्सेस नियंत्रण होंगे, भले ही अन्य नियमों को संशोधित कर रहे हों।
लेकिन रुकिए, और भी बहुत कुछ है!
यदि आप जारी रखते हैं तो आप सीखेंगे:
- फायरस्टोर ईवेंट द्वारा ट्रिगर किए गए फ़ंक्शन को कैसे लिखें
- कई एमुलेटर में काम करने वाले परीक्षण कैसे बनाएं
15. क्लाउड फ़ंक्शन परीक्षण सेट करें
अब तक हमने अपने वेब ऐप के फ़्रंटएंड और फायरस्टोर सुरक्षा नियमों पर ध्यान केंद्रित किया है। लेकिन यह ऐप यूजर के कार्ट को अप टू डेट रखने के लिए क्लाउड फंक्शंस का भी इस्तेमाल करता है, इसलिए हम उस कोड को भी टेस्ट करना चाहते हैं।
एमुलेटर सूट क्लाउड फ़ंक्शंस का परीक्षण करना इतना आसान बनाता है, यहां तक कि ऐसे फ़ंक्शन भी जो क्लाउड फायरस्टोर और अन्य सेवाओं का उपयोग करते हैं।
संपादक में, emulators-codelab/codelab-initial-state/functions/test.js
फ़ाइल खोलें और फ़ाइल में अंतिम परीक्षण तक स्क्रॉल करें। अभी, इसे लंबित के रूप में चिह्नित किया गया है:
// REMOVE .skip FROM THIS LINE
describe.skip("adding an item to the cart recalculates the cart total. ", () => {
// ...
it("should sum the cost of their items", async () => {
...
});
});
परीक्षण को सक्षम करने के लिए, .skip
निकालें, तो यह इस तरह दिखता है:
describe("adding an item to the cart recalculates the cart total. ", () => {
// ...
it("should sum the cost of their items", async () => {
...
});
});
इसके बाद, फ़ाइल के शीर्ष पर REAL_FIREBASE_PROJECT_ID
चर खोजें और इसे अपने वास्तविक Firebase प्रोजेक्ट आईडी में बदलें।
// CHANGE THIS LINE
const REAL_FIREBASE_PROJECT_ID = "changeme";
अगर आप अपनी प्रोजेक्ट आईडी भूल गए हैं तो आप फायरबेस कंसोल में प्रोजेक्ट सेटिंग्स में अपना फायरबेस प्रोजेक्ट आईडी ढूंढ सकते हैं:
16. कार्य परीक्षणों के माध्यम से चलो
चूंकि यह परीक्षण क्लाउड फायरस्टोर और क्लाउड फ़ंक्शंस के बीच बातचीत को मान्य करता है, इसमें पिछले कोडलैब में परीक्षणों की तुलना में अधिक सेटअप शामिल है। आइए इस परीक्षण के माध्यम से चलते हैं और यह अनुमान लगाते हैं कि यह क्या उम्मीद करता है।
कार्ट बनाएं
क्लाउड फ़ंक्शंस एक विश्वसनीय सर्वर परिवेश में चलते हैं और व्यवस्थापक SDK द्वारा उपयोग किए जाने वाले सेवा खाता प्रमाणीकरण का उपयोग कर सकते हैं। सबसे पहले, आप इनिशियलाइज़ ऐप के बजाय initializeAdminApp
का उपयोग करके एक ऐप को initializeApp
। फिर, आप उस कार्ट के लिए एक DocumentReference बनाते हैं जिसमें हम आइटम जोड़ेंगे और कार्ट को इनिशियलाइज़ करेंगे:
it("should sum the cost of their items", async () => {
const db = firebase
.initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
.firestore();
// Setup: Initialize cart
const aliceCartRef = db.doc("carts/alice")
await aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });
...
});
फ़ंक्शन को ट्रिगर करें
फिर, फ़ंक्शन को ट्रिगर करने के लिए हमारे कार्ट दस्तावेज़ के items
उप-संग्रह में दस्तावेज़ जोड़ें। यह सुनिश्चित करने के लिए दो आइटम जोड़ें कि आप फ़ंक्शन में होने वाले जोड़ का परीक्षण कर रहे हैं।
it("should sum the cost of their items", async () => {
const db = firebase
.initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
.firestore();
// Setup: Initialize cart
const aliceCartRef = db.doc("carts/alice")
await aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });
// Trigger calculateCart by adding items to the cart
const aliceItemsRef = aliceCartRef.collection("items");
await aliceItemsRef.doc("doc1").set({name: "nectarine", price: 2.99});
await aliceItemsRef.doc("doc2").set({ name: "grapefruit", price: 6.99 });
...
});
});
परीक्षण अपेक्षाएं निर्धारित करें
कार्ट दस्तावेज़ में किसी भी परिवर्तन के लिए श्रोता को पंजीकृत करने के लिए onSnapshot()
का उपयोग करें। onSnapshot()
एक फ़ंक्शन देता है जिसे आप श्रोता को अपंजीकृत करने के लिए कॉल कर सकते हैं।
इस परीक्षण के लिए, दो आइटम जोड़ें जिनकी कीमत एक साथ $9.98 है। फिर, जांचें कि कार्ट में अपेक्षित itemCount
और totalPrice
है या नहीं। यदि ऐसा है, तो समारोह ने अपना काम किया।
it("should sum the cost of their items", (done) => {
const db = firebase
.initializeAdminApp({ projectId: REAL_FIREBASE_PROJECT_ID })
.firestore();
// Setup: Initialize cart
const aliceCartRef = db.doc("carts/alice")
aliceCartRef.set({ ownerUID: "alice", totalPrice: 0 });
// Trigger calculateCart by adding items to the cart
const aliceItemsRef = aliceCartRef.collection("items");
aliceItemsRef.doc("doc1").set({name: "nectarine", price: 2.99});
aliceItemsRef.doc("doc2").set({ name: "grapefruit", price: 6.99 });
// Listen for every update to the cart. Every time an item is added to
// the cart's subcollection of items, the function updates `totalPrice`
// and `itemCount` attributes on the cart.
// Returns a function that can be called to unsubscribe the listener.
await new Promise((resolve) => {
const unsubscribe = aliceCartRef.onSnapshot(snap => {
// If the function worked, these will be cart's final attributes.
const expectedCount = 2;
const expectedTotal = 9.98;
// When the `itemCount`and `totalPrice` match the expectations for the
// two items added, the promise resolves, and the test passes.
if (snap.data().itemCount === expectedCount && snap.data().totalPrice == expectedTotal) {
// Call the function returned by `onSnapshot` to unsubscribe from updates
unsubscribe();
resolve();
};
});
});
});
});
17. परीक्षण चलाएँ
आपके पास अभी भी पिछले परीक्षणों से चलने वाले अनुकरणकर्ता हो सकते हैं। यदि नहीं, तो एमुलेटर शुरू करें। कमांड लाइन से, रन
$ firebase emulators:start --import=./seed
एक नया टर्मिनल टैब खोलें (एमुलेटर को चालू रहने दें) और फंक्शन डायरेक्टरी में चले जाएं। आपके पास अभी भी सुरक्षा नियमों के परीक्षण से यह खुला हो सकता है।
$ cd functions
अब यूनिट टेस्ट चलाएं, आपको कुल 5 टेस्ट देखने चाहिए:
$ npm test > functions@ test .../emulators-codelab/codelab-initial-state/functions > mocha shopping cart creation ✓ can be created by the cart owner (82ms) shopping cart reads, updates, and deletes ✓ cart can be read by the cart owner (42ms) shopping cart items ✓ items can be read by the cart owner (40ms) ✓ items can be added by the cart owner adding an item to the cart recalculates the cart total. 1) should sum the cost of their items 4 passing (2s) 1 failing
यदि आप विशिष्ट विफलता को देखते हैं, तो यह एक टाइमआउट त्रुटि प्रतीत होती है। ऐसा इसलिए है क्योंकि परीक्षण फ़ंक्शन के ठीक से अपडेट होने की प्रतीक्षा कर रहा है, लेकिन ऐसा कभी नहीं होता है। अब, हम परीक्षण को संतुष्ट करने के लिए फ़ंक्शन लिखने के लिए तैयार हैं।
18. एक फ़ंक्शन लिखें
इस परीक्षण को ठीक करने के लिए, आपको functions/index.js
में फ़ंक्शन को अपडेट करना होगा। हालांकि इसमें से कुछ फ़ंक्शन लिखा गया है, यह पूर्ण नहीं है। इस प्रकार फ़ंक्शन वर्तमान में दिखता है:
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
let totalPrice = 125.98;
let itemCount = 8;
try {
const cartRef = db.collection("carts").doc(context.params.cartId);
await cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
});
फ़ंक्शन कार्ट संदर्भ को सही ढंग से सेट कर रहा है, लेकिन फिर totalPrice
और itemCount
के मानों की गणना करने के बजाय, यह उन्हें हार्डकोड वाले में अपडेट करता है।
के माध्यम से प्राप्त करें और पुनरावृति करें
items
उपसंग्रह
items
itemsSnap
होने के लिए एक नया स्थिरांक, आइटम स्नैप प्रारंभ करें। फिर, संग्रह में सभी दस्तावेजों के माध्यम से पुनरावृति करें।
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
try {
let totalPrice = 125.98;
let itemCount = 8;
const cartRef = db.collection("carts").doc(context.params.cartId);
// ADD LINES FROM HERE
const itemsSnap = await cartRef.collection("items").get();
itemsSnap.docs.forEach(item => {
const itemData = item.data();
})
// TO HERE
return cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
});
कुल मूल्य और आइटम गणना की गणना करें
सबसे पहले, कुल मूल्य और totalPrice
के itemCount
को शून्य पर प्रारंभ करें।
फिर, हमारे पुनरावृत्ति ब्लॉक में तर्क जोड़ें। सबसे पहले, जांचें कि आइटम की कीमत है। यदि आइटम में निर्दिष्ट मात्रा नहीं है, तो इसे 1
पर डिफ़ॉल्ट होने दें। फिर, मात्रा को itemCount
के चल रहे कुल में जोड़ें। अंत में, आइटम की कीमत को कुल मूल्य के रनिंग टोटल में मात्रा से गुणा करके totalPrice
:
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
try {
// CHANGE THESE LINES
let totalPrice = 0;
let itemCount = 0;
const cartRef = db.collection("carts").doc(context.params.cartId);
const itemsSnap = await cartRef.collection("items").get();
itemsSnap.docs.forEach(item => {
const itemData = item.data();
// ADD LINES FROM HERE
if (itemData.price) {
// If not specified, the quantity is 1
const quantity = itemData.quantity ? itemData.quantity : 1;
itemCount += quantity;
totalPrice += (itemData.price * quantity);
}
// TO HERE
})
await cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
}
});
आप डीबग सफलता और त्रुटि स्थिति में सहायता के लिए लॉगिंग भी जोड़ सकते हैं:
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
console.log(`onWrite: ${change.after.ref.path}`);
if (!change.after.exists) {
// Ignore deletes
return;
}
let totalPrice = 0;
let itemCount = 0;
try {
const cartRef = db.collection("carts").doc(context.params.cartId);
const itemsSnap = await cartRef.collection("items").get();
itemsSnap.docs.forEach(item => {
const itemData = item.data();
if (itemData.price) {
// If not specified, the quantity is 1
const quantity = (itemData.quantity) ? itemData.quantity : 1;
itemCount += quantity;
totalPrice += (itemData.price * quantity);
}
});
await cartRef.update({
totalPrice,
itemCount
});
// OPTIONAL LOGGING HERE
console.log("Cart total successfully recalculated: ", totalPrice);
} catch(err) {
// OPTIONAL LOGGING HERE
console.warn("update error", err);
}
});
19. फिर से चलाएँ परीक्षण
कमांड लाइन पर, सुनिश्चित करें कि एमुलेटर अभी भी चल रहे हैं और परीक्षण फिर से चलाएँ। आपको एमुलेटर को पुनरारंभ करने की आवश्यकता नहीं है क्योंकि वे स्वचालित रूप से कार्यों में परिवर्तन उठाते हैं। आपको सभी परीक्षण पास होते हुए देखने चाहिए:
$ npm test > functions@ test .../emulators-codelab/codelab-initial-state/functions > mocha shopping cart creation ✓ can be created by the cart owner (306ms) shopping cart reads, updates, and deletes ✓ cart can be read by the cart owner (59ms) shopping cart items ✓ items can be read by the cart owner ✓ items can be added by the cart owner adding an item to the cart recalculates the cart total. ✓ should sum the cost of their items (800ms) 5 passing (1s)
अच्छी नौकरी!
20. स्टोरफ़्रंट UI का उपयोग करके इसे आज़माएं
अंतिम परीक्षण के लिए, वेब ऐप ( http://localhost:5000/ ) पर वापस लौटें और कार्ट में एक आइटम जोड़ें।
पुष्टि करें कि कार्ट सही कुल के साथ अपडेट होता है। ज़बरदस्त!
संक्षिप्त
आप Firebase के लिए Cloud Functions और Cloud Firestore के बीच एक जटिल परीक्षण केस से गुजरे हैं। आपने टेस्ट पास करने के लिए क्लाउड फंक्शन लिखा है। आपने यह भी पुष्टि की है कि नई कार्यक्षमता UI में काम कर रही है! आपने यह सब स्थानीय रूप से किया, एमुलेटर को अपनी मशीन पर चलाकर।
आपने एक वेब क्लाइंट भी बनाया है जो स्थानीय एमुलेटर के खिलाफ चल रहा है, डेटा की सुरक्षा के लिए सुरक्षा नियमों के अनुरूप है, और स्थानीय एमुलेटर का उपयोग करके सुरक्षा नियमों का परीक्षण किया है।