פיתוח מקומי עם Firebase Emulator Suite

1. לפני שמתחילים

כלים עורפיים ללא שרת כמו Cloud Firestore ו-Cloud Functions קלים מאוד לשימוש, אך יכולים להיות קשים לבדיקה. Firebase Local Emulator Suite מאפשר לך להפעיל גרסאות מקומיות של שירותים אלה על מכונת הפיתוח שלך כדי שתוכל לפתח את האפליקציה שלך במהירות ובבטחה.

דרישות מוקדמות

  • עורך פשוט כגון Visual Studio Code, Atom או Sublime Text
  • Node.js 10.0.0 ומעלה (כדי להתקין את Node.js, השתמש ב-nvm , כדי לבדוק את הגרסה שלך, הרץ את node --version )
  • Java 7 ומעלה (כדי להתקין Java השתמש בהוראות אלה , כדי לבדוק את הגרסה שלך, הפעל java -version )

מה תעשה

במעבדת הקוד הזה, תפעיל ותנקה באגים באפליקציית קניות מקוונת פשוטה המופעלת על ידי מספר שירותי Firebase:

  • Cloud Firestore: מסד נתונים NoSQL הניתן להרחבה גלובלית ללא שרתים עם יכולות בזמן אמת.
  • פונקציות ענן : קוד backend ללא שרת הפועל בתגובה לאירועים או בקשות HTTP.
  • אימות Firebase : שירות אימות מנוהל המשתלב עם מוצרי Firebase אחרים.
  • אירוח Firebase : אירוח מהיר ומאובטח עבור אפליקציות אינטרנט.

תחבר את האפליקציה ל-Emulator Suite כדי לאפשר פיתוח מקומי.

2589e2f95b74fa88.png

תלמד גם כיצד:

  • כיצד לחבר את האפליקציה שלך ל-Emulator Suite וכיצד מתחברים האמולטורים השונים.
  • כיצד פועלים כללי האבטחה של Firebase וכיצד לבדוק את כללי האבטחה של Firestore מול אמולטור מקומי.
  • כיצד לכתוב פונקציית Firebase המופעלת על ידי אירועי Firestore וכיצד לכתוב מבחני אינטגרציה הפועלים מול Emulator Suite.

2. הגדר

קבל את קוד המקור

במעבדת הקוד הזה, אתה מתחיל עם גרסה של דוגמה של The Fire Store שכמעט הושלמה, אז הדבר הראשון שאתה צריך לעשות הוא לשכפל את קוד המקור:

$ git clone https://github.com/firebase/emulators-codelab.git

לאחר מכן עבור לספריית Codelab, שם תעבוד במשך שאר הקוד Lab:

$ cd emulators-codelab/codelab-initial-state

כעת, התקן את התלות כדי שתוכל להפעיל את הקוד. אם אתה מחובר לאינטרנט איטי יותר, הדבר עשוי להימשך דקה או שתיים:

# Move into the functions directory
$ cd functions

# Install dependencies
$ npm install

# Move back into the previous directory
$ cd ../

קבל את Firebase CLI

חבילת האמולטור היא חלק מ-Firebase CLI (ממשק שורת פקודה) שניתן להתקין במחשב שלך באמצעות הפקודה הבאה:

$ npm install -g firebase-tools

לאחר מכן, אשר שיש לך את הגרסה העדכנית ביותר של ה-CLI. מעבד קוד זה אמור לעבוד עם גרסה 9.0.0 ומעלה, אך גרסאות מאוחרות יותר כוללות תיקוני באגים נוספים.

$ firebase --version
9.6.0

התחבר לפרויקט Firebase שלך

אם אין לך פרויקט Firebase, במסוף Firebase צור פרויקט Firebase חדש. רשום את מזהה הפרויקט שתבחר, תזדקק לו מאוחר יותר.

כעת עלינו לחבר את הקוד הזה לפרויקט Firebase שלך. תחילה הפעל את הפקודה הבאה כדי להיכנס ל-Firebase CLI:

$ firebase login

לאחר מכן הפעל את הפקודה הבאה כדי ליצור כינוי לפרויקט. החלף $YOUR_PROJECT_ID במזהה של פרויקט Firebase שלך.

$ firebase use $YOUR_PROJECT_ID

עכשיו אתה מוכן להפעיל את האפליקציה!

3. הפעל את האמולטורים

בחלק זה, תפעיל את האפליקציה באופן מקומי. זה אומר שהגיע הזמן לאתחל את חבילת האמולטור.

הפעל את האמולטורים

מתוך ספריית המקור של codelab, הפעל את הפקודה הבאה כדי להפעיל את האמולטורים:

$ 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.

ברגע שתראה את הודעת כל האמולטורים התחילו , האפליקציה מוכנה לשימוש.

חבר את אפליקציית האינטרנט לאמולטורים

בהתבסס על הטבלה ביומנים אנו יכולים לראות שהאמולטור Cloud Firestore מאזין ביציאה 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 . אנו יכולים לראות שהקוד ניגש למופעי Firestore ו-Auth הסטנדרטיים:

public/js/homepage.js

  const auth = firebaseApp.auth();
  const db = firebaseApp.firestore();

בואו נעדכן את אובייקטי ה- db וה- auth כך שיצביעו על האמולטורים המקומיים:

public/js/homepage.js

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

כעת כאשר האפליקציה פועלת על המחשב המקומי שלך (מוגש על ידי אמולטור Hosting), לקוח Firestore מצביע גם על האמולטור המקומי ולא על מסד נתונים ייצור.

פתח את EmulatorUI

בדפדפן האינטרנט שלך, נווט אל http://127.0.0.1:4000/ . אתה אמור לראות את ממשק המשתמש של Emulator Suite.

מסך הבית של ממשק המשתמש האמולטורים

לחץ כדי לראות את ממשק המשתמש של אמולטור Firestore. אוסף items כבר מכיל נתונים בגלל הנתונים שיובאו עם הדגל --import .

4ef88d0148405d36.png

4. הפעל את האפליקציה

פתח את האפליקציה

בדפדפן האינטרנט שלך, נווט אל http://127.0.0.1:5000 ואתה אמור לראות את The Fire Store פועל באופן מקומי במחשב שלך!

939f87946bac2ee4.png

השתמש באפליקציה

בחר פריט בדף הבית ולחץ על הוסף לעגלה . למרבה הצער, תתקל בשגיאה הבאה:

a11bd59933a8e885.png

בוא נתקן את הבאג הזה! מכיוון שהכל פועל באמולטורים, אנו יכולים להתנסות ולא לדאוג להשפיע על נתונים אמיתיים.

5. ניפוי באגים באפליקציה

מצא את הבאג

אוקיי בוא נסתכל במסוף המפתחים של Chrome. הקש Control+Shift+J (Windows, Linux, Chrome OS) או Command+Option+J (Mac) כדי לראות את השגיאה במסוף:

74c45df55291dab1.png

נראה שהייתה שגיאה כלשהי בשיטת addToCart , בואו נסתכל על זה. איפה אנחנו מנסים לגשת למשהו שנקרא uid בשיטה הזו ולמה שזה יהיה null ? כרגע השיטה נראית כך ב- public/js/homepage.js :

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

אהה! אנחנו לא מחוברים לאפליקציה. לפי מסמכי האימות של Firebase , כאשר אנחנו לא מחוברים, auth.currentUser הוא null . בוא נוסיף צ'ק על זה:

public/js/homepage.js

  addToCart(id, itemData) {
    // ADD THESE LINES
    if (this.auth.currentUser === null) {
      this.showError("You must be signed in!");
      return;
    }

    // ...
  }

בדוק את האפליקציה

כעת, רענן את הדף ולאחר מכן לחץ על הוסף לעגלה . אתה אמור לקבל שגיאה יפה יותר הפעם:

c65f6c05588133f7.png

אבל אם תלחץ על כניסה בסרגל הכלים העליון ואז תלחץ שוב על הוסף לעגלה , תראה שהסל מעודכן.

עם זאת, לא נראה שהמספרים נכונים בכלל:

239f26f02f959eef.png

אל תדאג, אנחנו נתקן את הבאג הזה בקרוב. ראשית, בואו נצלול לעומק מה באמת קרה כשהוספתם פריט לעגלת הקניות שלכם.

6. מפעילים פונקציות מקומיות

לחיצה על הוסף לסל מפעילה שרשרת אירועים הכוללת מספר אמולטורים. ביומני Firebase CLI, אתה אמור לראות משהו כמו ההודעות הבאות לאחר הוספת פריט לעגלת הקניות שלך:

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

היו ארבעה אירועים מרכזיים שהתרחשו כדי לייצר את היומנים האלה ואת עדכון ממשק המשתמש שראית:

68c9323f2ad10f7a.png

1) Firestore Write - לקוח

מסמך חדש נוסף לאוסף Firestore /carts/{cartId}/items/{itemId}/ . אתה יכול לראות את הקוד הזה בפונקציית addToCart בתוך public/js/homepage.js :

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 :

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) Firestore Write - Admin

הפונקציה calculateCart קוראת את כל הפריטים בעגלה ומסכמת את הכמות והמחיר הכוללים, ואז היא מעדכנת את מסמך ה-"cart" בסיכומים החדשים (ראה cartRef.update(...) למעלה).

4) Firestore Read - לקוח

חזית האינטרנט רשומה לקבלת עדכונים לגבי שינויים בעגלה. הוא מקבל עדכון בזמן אמת לאחר שפונקציית הענן כותבת את הסכומים החדשים ומעדכנת את ממשק המשתמש, כפי שניתן לראות ב- public/js/homepage.js :

public/js/homepage.js

this.cartUnsub = cartRef.onSnapshot(cart => {
   // The cart document was changed, update the UI
   // ...
});

לסכם

עבודה נחמדה! אתה פשוט מגדיר אפליקציה מקומית לחלוטין המשתמשת בשלושה אמולטורים שונים של Firebase לבדיקה מקומית מלאה.

db82eef1706c9058.gif

אבל רגע, יש עוד! בסעיף הבא תלמדו:

  • כיצד לכתוב בדיקות יחידות המשתמשות באמולטורים של Firebase.
  • כיצד להשתמש באמולטורים של Firebase כדי לנפות באגים בכללי האבטחה שלך.

7. צור כללי אבטחה המותאמים לאפליקציה שלך

אפליקציית האינטרנט שלנו קוראת וכותבת נתונים אבל עד כה לא באמת דאגנו לגבי האבטחה בכלל. Cloud Firestore משתמשת במערכת הנקראת "כללי אבטחה" כדי להצהיר למי יש גישה לקריאה ולכתיבה של נתונים. חבילת האמולטור היא דרך מצוינת ליצור אב טיפוס של כללים אלה.

בעורך, פתח את הקובץ 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. גישה מאובטחת לעגלה

שני הכשלים הראשונים הם מבחני "עגלת קניות" שבודקים כי:

  • משתמשים יכולים ליצור ולעדכן רק את העגלות שלהם
  • משתמשים יכולים לקרוא רק את העגלות שלהם

functions/test.js

  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 Authentication , האובייקט request.auth מתאר את המשתמש שמבצע את הבקשה.

10. בדוק את הגישה לעגלה

חבילת האמולטור מעדכנת אוטומטית את הכללים בכל פעם ש- firestore.rules נשמר. אתה יכול לאשר שהאמולטור מעודכן את הכללים על ידי חיפוש בכרטיסייה של הפעלת האמולטור עבור ההודעה 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. בדוק את זרימת "הוסף לעגלה" בממשק המשתמש

נכון לעכשיו, למרות שבעלי עגלות קוראים וכותבים לעגלה שלהם, הם לא יכולים לקרוא או לכתוב פריטים בודדים בעגלה שלהם. הסיבה לכך היא שבעוד לבעלים יש גישה למסמך העגלה, אין להם גישה לאוסף הפריטים של העגלה .

זהו מצב שבור עבור משתמשים.

חזור לממשק המשתמש של האינטרנט, שפועל ב- 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
    }));
  });

אז נוכל לכתוב כלל שמאפשר גישה אם למשתמש הנוכחי יש את אותו UID כמו הבעלים-UID במסמך העגלה. מכיוון שאין צורך לציין כללים שונים עבור create, update, delete , אתה יכול להשתמש בכלל write , אשר חל על כל הבקשות שמשנות נתונים.

עדכן את הכלל עבור המסמכים בתת-אוסף הפריטים. get לתנאי היא קריאת ערך מ-Firestore - במקרה זה, ה- 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

אבל רגע, יש עוד!

אם תמשיך הלאה תלמד:

  • כיצד לכתוב פונקציה המופעלת על ידי אירוע Firestore
  • כיצד ליצור מבחנים שעובדים על פני מספר אמולטורים

15. הגדר בדיקות Cloud Functions

עד כה התמקדנו בחזית אפליקציית האינטרנט שלנו ובכללי האבטחה של Firestore. אבל האפליקציה הזו משתמשת גם ב-Cloud Functions כדי לעדכן את העגלה של המשתמש, אז אנחנו רוצים לבדוק גם את הקוד הזה.

חבילת האמולטור מקלה כל כך לבדוק את פונקציות הענן, אפילו פונקציות המשתמשות ב-Cloud Firestore ובשירותים אחרים.

בעורך, פתח את הקובץ 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";

אם שכחת את מזהה הפרויקט שלך, תוכל למצוא את מזהה הפרויקט שלך ב-Firebase בהגדרות הפרויקט ב-Firebase Console:

d6d0429b700d2b21.png

16. עברו על מבחני פונקציות

מכיוון שבדיקה זו מאמתת את האינטראקציה בין Cloud Firestore ל-Cloud Functions, היא כרוכה בהגדרה רבה יותר מהבדיקות במעבדות הקוד הקודמות. בואו נעבור על המבחן הזה ונקבל מושג למה הוא מצפה.

צור עגלה

פונקציות ענן פועלות בסביבת שרת מהימנה ויכולות להשתמש באימות חשבון השירות המשמש את ה-Admin 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

אתחול קבוע חדש, itemsSnap , כדי להיות תת-אוסף items . לאחר מכן, חזור על כל המסמכים באוסף.

// 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. נסה זאת באמצעות ממשק המשתמש של Storefront

למבחן הסופי, חזור לאפליקציית האינטרנט ( http://127.0.0.1:5000/ ) והוסף פריט לעגלת הקניות.

69ad26cee520bf24.png

אשר שהעגלה מתעדכנת עם הסכום הנכון. פַנטַסטִי!

לסכם

עברת על מקרה בדיקה מורכב בין Cloud Functions for Firebase ו-Cloud Firestore. כתבת פונקציית ענן כדי שהבדיקה תעבור. אישרת גם שהפונקציונליות החדשה פועלת בממשק המשתמש! עשית את כל זה באופן מקומי, הפעלת את האמולטורים על המחשב שלך.

יצרת גם לקוח אינטרנט שפועל נגד האמולטורים המקומיים, התאמת כללי אבטחה להגנה על הנתונים, ובדקת את כללי האבטחה באמצעות האמולטורים המקומיים.

c6a7aeb91fe97a64.gif