फायरबेस एमुलेटर सूट के साथ स्थानीय विकास

1. शुरू करने से पहले

क्लाउड फायरस्टोर और क्लाउड फ़ंक्शंस जैसे सर्वर रहित बैकएंड टूल का उपयोग करना बहुत आसान है, लेकिन परीक्षण करना कठिन हो सकता है। फायरबेस लोकल एम्यूलेटर सूट आपको अपनी विकास मशीन पर इन सेवाओं के स्थानीय संस्करण चलाने की अनुमति देता है ताकि आप अपने ऐप को जल्दी और सुरक्षित रूप से विकसित कर सकें।

आवश्यक शर्तें

  • एक साधारण संपादक जैसे विज़ुअल स्टूडियो कोड, एटम या सबलाइम टेक्स्ट
  • Node.js 10.0.0 या उच्चतर (Node.js स्थापित करने के लिए, nvm का उपयोग करें , अपने संस्करण की जांच करने के लिए, node --version चलाएँ)
  • जावा 7 या उच्चतर (जावा को स्थापित करने के लिए इन निर्देशों का उपयोग करें , अपने संस्करण की जांच करने के लिए, java -version चलाएं)

तुम क्या करोगे

इस कोडलैब में, आप एक साधारण ऑनलाइन शॉपिंग ऐप चलाएंगे और डिबग करेंगे जो कई फायरबेस सेवाओं द्वारा संचालित है:

  • क्लाउड फायरस्टोर: रीयल-टाइम क्षमताओं के साथ विश्व स्तर पर स्केलेबल, सर्वर रहित, नोएसक्यूएल डेटाबेस।
  • क्लाउड फ़ंक्शंस : एक सर्वर रहित बैकएंड कोड जो ईवेंट या HTTP अनुरोधों के जवाब में चलता है।
  • फायरबेस प्रमाणीकरण : एक प्रबंधित प्रमाणीकरण सेवा जो अन्य फायरबेस उत्पादों के साथ एकीकृत होती है।
  • फायरबेस होस्टिंग : वेब ऐप्स के लिए तेज़ और सुरक्षित होस्टिंग।

स्थानीय विकास को सक्षम करने के लिए आप ऐप को एमुलेटर सूट से जोड़ेंगे।

2589e2f95b74fa88.png

आप यह भी सीखेंगे कि कैसे:

  • अपने ऐप को एमुलेटर सूट से कैसे कनेक्ट करें और विभिन्न एमुलेटर कैसे जुड़े हैं।
  • फायरबेस सुरक्षा नियम कैसे काम करते हैं और स्थानीय एमुलेटर के खिलाफ फायरस्टार सुरक्षा नियमों का परीक्षण कैसे करें।
  • फायरस्टोर इवेंट्स द्वारा ट्रिगर किए गए फायरबेस फ़ंक्शन को कैसे लिखें और एम्यूलेटर सूट के खिलाफ चलने वाले एकीकरण परीक्षण कैसे लिखें।

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 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://127.0.0.1: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://127.0.0.1:4000                │
└─────────────────────────────────────────────────────────────┘

┌────────────────┬────────────────┬─────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Functions      │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Hosting        │ 127.0.0.1:5000 │ n/a                             │
└────────────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at 127.0.0.1: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 │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Functions      │ 127.0.0.1:5001 │ http://127.0.0.1:4000/functions │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Hosting        │ 127.0.0.1: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 === "127.0.0.1") {
    console.log("127.0.0.1 detected!");
    auth.useEmulator("http://127.0.0.1:9099");
    db.useEmulator("127.0.0.1", 8080);
  }

अब जब ऐप आपकी स्थानीय मशीन (होस्टिंग एमुलेटर द्वारा सेवा) पर चल रहा है, तो फायरस्टोर क्लाइंट उत्पादन डेटाबेस के बजाय स्थानीय एमुलेटर पर भी इशारा करता है।

एमुलेटरयूआई खोलें

अपने वेब ब्राउज़र में, http://127.0.0.1:4000/ पर नेविगेट करें। आपको एम्यूलेटर सूट यूआई देखना चाहिए।

एमुलेटर यूआई होम स्क्रीन

फायरस्टार एम्यूलेटर के लिए यूआई देखने के लिए क्लिक करें। --import फ़्लैग के साथ आयात किए गए डेटा के कारण items संग्रह में पहले से ही डेटा है।

4ef88d0148405d36.png

4. ऐप चलाएं

ऐप खोलें

अपने वेब ब्राउज़र में, http://127.0.0.1:5000 पर नेविगेट करें और आपको अपनी मशीन पर स्थानीय रूप से चल रहे फायर स्टोर को देखना चाहिए!

939f87946bac2ee4.png

ऐप का प्रयोग करें

होमपेज पर कोई आइटम चुनें और कार्ट में जोड़ें पर क्लिक करें। दुर्भाग्य से, आप निम्न त्रुटि में चलेंगे:

a11bd59933a8e885.png

आइए उस बग को ठीक करें! क्योंकि सब कुछ एमुलेटर में चल रहा है, हम प्रयोग कर सकते हैं और वास्तविक डेटा को प्रभावित करने की चिंता नहीं कर सकते।

5. ऐप को डीबग करें

बग का पता लगाएं

ठीक है, आइए क्रोम डेवलपर कंसोल में देखें। कंसोल पर त्रुटि देखने के लिए Control+Shift+J (Windows, Linux, Chrome OS) या Command+Option+J (Mac) दबाएं:

74c45df55291dab1.png

ऐसा लगता है कि 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 पर क्लिक करें। आपको इस बार एक अच्छी त्रुटि मिलनी चाहिए:

c65f6c05588133f7.png

लेकिन अगर आप ऊपरी टूलबार में साइन इन पर क्लिक करते हैं और फिर से कार्ट में जोड़ें पर क्लिक करते हैं, तो आप देखेंगे कि कार्ट अपडेट हो गया है।

हालाँकि, ऐसा नहीं लगता कि संख्याएँ बिल्कुल सही हैं:

239f26f02f959eef.png

चिंता न करें, हम जल्द ही उस बग को ठीक कर देंगे। सबसे पहले, जब आपने अपने कार्ट में कोई आइटम जोड़ा तो वास्तव में क्या हुआ, इसकी गहराई से जानकारी लें।

6. स्थानीय कार्य ट्रिगर करता है

ऐड टू कार्ट पर क्लिक करने से उन घटनाओं की एक श्रृंखला शुरू हो जाती है जिनमें कई एमुलेटर शामिल होते हैं। फायरबेस सीएलआई लॉग में, आपको अपने कार्ट में कोई आइटम जोड़ने के बाद निम्न संदेशों की तरह कुछ देखना चाहिए:

i  functions: Beginning execution of "calculateCart"
i  functions: Finished "calculateCart" in ~1s

उन लॉग और आपके द्वारा देखे गए UI अपडेट को उत्पन्न करने के लिए चार प्रमुख घटनाएं हुईं:

68c9323f2ad10f7a.png

1) फायरस्टोर राइट - क्लाइंट

फायरस्टोर संग्रह /carts/{cartId}/items/{itemId}/ में एक नया दस्तावेज़ जोड़ा गया है। आप इस कोड को public/js/homepage.js के अंदर addToCart फ़ंक्शन में देख सकते हैं:

सार्वजनिक/जेएस/होमपेज.जेएस

  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 में देख सकते हैं:

फ़ंक्शंस/इंडेक्स.जेएस

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
   // ...
});

संक्षिप्त

अच्छा काम! आपने बस एक पूरी तरह से स्थानीय ऐप सेट किया है जो पूरी तरह से स्थानीय परीक्षण के लिए तीन अलग-अलग फायरबेस एमुलेटर का उपयोग करता है।

db82eef1706c9058.gif

लेकिन रुकिए, और भी बहुत कुछ है! अगले भाग में आप सीखेंगे:

  • फायरबेस एमुलेटर का उपयोग करने वाले यूनिट टेस्ट कैसे लिखें।
  • अपने सुरक्षा नियमों को डीबग करने के लिए Firebase Emulators का उपयोग कैसे करें।

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} के भीतर बयानों को अपडेट करें:

firestore.rules

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 :

5680da418b420226.png

परीक्षणों को दोबारा चलाएं, और जांचें कि पहले दो परीक्षण अब पास हो गए हैं:

$ 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 में "कार्ट में जोड़ें" प्रवाह की जाँच करें

अभी, हालांकि कार्ट मालिक अपने कार्ट में पढ़ और लिख सकते हैं, वे अपने कार्ट में अलग-अलग आइटम पढ़ या लिख ​​नहीं सकते हैं। ऐसा इसलिए है क्योंकि मालिकों के पास कार्ट दस्तावेज़ तक पहुंच होती है, लेकिन उनके पास कार्ट के आइटम उपसंग्रह तक पहुंच नहीं होती है।

यह उपयोगकर्ताओं के लिए एक टूटी हुई स्थिति है।

वेब यूआई पर लौटें, जो http://127.0.0.1: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://127.0.0.1:5000 ) और कार्ट में एक आइटम जोड़ें। यह पुष्टि करने के लिए एक महत्वपूर्ण कदम है कि हमारे परीक्षण और नियम क्लाइंट द्वारा आवश्यक कार्यक्षमता से मेल खाते हैं। (याद रखें कि पिछली बार हमने कोशिश की थी कि यूआई उपयोगकर्ता अपने कार्ट में आइटम जोड़ने में असमर्थ थे!)

69ad26cee520bf24.png

जब firestore.rules सहेजे जाते हैं तो क्लाइंट स्वचालित रूप से नियमों को पुनः लोड करता है। तो, कार्ट में कुछ जोड़ने का प्रयास करें।

संक्षिप्त

अच्छा काम! आपने अभी-अभी अपने ऐप की सुरक्षा में सुधार किया है, इसे उत्पादन के लिए तैयार करने के लिए एक आवश्यक कदम! यदि यह एक प्रोडक्शन ऐप होता, तो हम इन परीक्षणों को अपने निरंतर एकीकरण पाइपलाइन में जोड़ सकते थे। इससे हमें आगे बढ़ने का भरोसा मिलेगा कि हमारे शॉपिंग कार्ट डेटा में ये एक्सेस कंट्रोल होंगे, भले ही दूसरे लोग नियमों में बदलाव कर रहे हों।

ba5440b193e75967.gif

लेकिन रुकिए, और भी बहुत कुछ है!

यदि आप जारी रखते हैं तो आप सीखेंगे:

  • फायरस्टोर इवेंट द्वारा ट्रिगर किए गए फ़ंक्शन को कैसे लिखें
  • एकाधिक इम्यूलेटर पर काम करने वाले परीक्षण कैसे बनाएं

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";

यदि आप अपना प्रोजेक्ट आईडी भूल गए हैं तो आप फायरबेस कंसोल में प्रोजेक्ट सेटिंग्स में अपना फायरबेस प्रोजेक्ट आईडी पा सकते हैं:

d6d0429b700d2b21.png

16. कार्य परीक्षणों के माध्यम से चलो

क्‍योंकि यह परीक्षण क्‍लाउड फायरस्‍टोर और क्‍लाउड फंक्‍शन के बीच इंटरएक्‍शन की पुष्टि करता है, इसमें पिछले कोडलैब के परीक्षणों की तुलना में अधिक सेटअप शामिल है। आइए इस परीक्षण के माध्यम से चलते हैं और यह अनुमान लगाते हैं कि यह क्या अपेक्षा करता है।

एक गाड़ी बनाएँ

क्लाउड फ़ंक्शंस एक विश्वसनीय सर्वर वातावरण में चलते हैं और व्यवस्थापक SDK द्वारा उपयोग किए जाने वाले सेवा खाता प्रमाणीकरण का उपयोग कर सकते हैं। सबसे पहले, आप initializeApp के बजाय initializeAdminApp का उपयोग करके एक ऐप को इनिशियलाइज़ करते हैं। फिर, आप उस कार्ट के लिए एक डॉक्यूमेंट रेफरेंस बनाते हैं जिसमें हम आइटम जोड़ेंगे और कार्ट को इनिशियलाइज़ करेंगे:

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. स्टोरफ्रंट यूआई का उपयोग करके इसे आज़माएं

अंतिम परीक्षण के लिए, वेब ऐप पर वापस लौटें ( http://127.0.0.1:5000/ ) और कार्ट में एक आइटम जोड़ें।

69ad26cee520bf24.png

पुष्टि करें कि कार्ट सही योग के साथ अपडेट होता है। ज़बरदस्त!

संक्षिप्त

आप Firebase और Cloud Firestore के लिए Cloud Functions के बीच एक जटिल परीक्षण मामले से गुजर चुके हैं। टेस्ट पास करने के लिए आपने क्लाउड फ़ंक्शन लिखा था। आपने यह भी पुष्टि की है कि यूआई में नई कार्यक्षमता काम कर रही है! आपने यह सब स्थानीय रूप से किया है, एमुलेटर को अपनी मशीन पर चला रहे हैं।

आपने एक वेब क्लाइंट भी बनाया है जो स्थानीय एमुलेटर के खिलाफ चल रहा है, डेटा की सुरक्षा के लिए सुरक्षा नियमों को तैयार किया है, और स्थानीय एमुलेटर का उपयोग करके सुरक्षा नियमों का परीक्षण किया है।

c6a7aeb91fe97a64.gif