使用 Azure Cosmos DB 適用於 MongoDB 的 API 建立 Angular 應用程式 - 將 CRUD 函式新增至應用程式

適用於: MongoDB

這個多部分的教學課程示範如何使用 Express 和 Angular 來建立以 Node.js 撰寫的新應用程式,然後將其連線至使用適用於 MongoDB 的 Azure Cosmos DB API 設定的 Azure Cosmos DB 帳戶。 本教學課程的第 6 部分是以第 5 部分為基礎並涵蓋下列工作:

  • 針對 Hero 服務新增 Post、Put 和 Delete 函式
  • 執行應用程式

必要條件

開始本教學課程的這個部分之前,請確定您已完成本教學課程第 5 部分中的步驟。

提示

本教學課程會為您解說逐步建置應用程式的步驟。 如果您需要下載已完成的專案,您可以從 GitHub 上的 angular-cosmosdb 存放庫取得已完成的應用程式。

將 Post 函式新增至 Hero 服務

  1. 在 Visual Studio Code 中,按 [分割編輯器] 按鈕 ,將 routes.jshero.service.js 並排開啟。

    您會看到 routes.js 第 7 行正在呼叫 hero.service.js 中第 5 行上的 getHeroes 函式。 我們需要針對 post、put 和 delete 函式建立此相同配對。

    routes.js and hero.service.js in Visual Studio Code

    讓我們開始撰寫 Hero 服務的程式碼。

  2. 將下列程式碼複製到 hero.service.js 中的 getHeroes 函式之後、module.exports 之前。 此程式碼:

    • 使用 Hero 模型來張貼新 hero。
    • 檢查回應,查看是否有錯誤並傳回狀態值為 500。
    function postHero(req, res) {
      const originalHero = { uid: req.body.uid, name: req.body.name, saying: req.body.saying };
      const hero = new Hero(originalHero);
      hero.save(error => {
        if (checkServerError(res, error)) return;
        res.status(201).json(hero);
        console.log('Hero created successfully!');
      });
    }
    
    function checkServerError(res, error) {
      if (error) {
        res.status(500).send(error);
        return error;
      }
    }
    
  3. hero.service.js 中,更新 module.exports 以包含新的 postHero 函式。

    module.exports = {
      getHeroes,
      postHero
    };
    
  4. routes.js 中,在 get 路由器之後為 post 函式新增路由器。 此路由器會一次張貼一個 Hero。 以這種方式建構路由器檔案,可清楚顯示所有可用的 API 端點並離開的實際工作hero.service.js檔案。

    router.post('/hero', (req, res) => {
      heroService.postHero(req, res);
    });
    
  5. 執行應用程式,檢查一切是否運作正常。 在 Visual Studio Code 中,儲存您的所有變更,選取左側的 [偵錯] 按鈕 ,然後選取 [開始偵錯] 按鈕

  6. 現在返回您的網際網路瀏覽器,並且按 F12 (在大部分的機器上) 開啟開發人員工具 [網路] 索引標籤。 瀏覽至 http://localhost:3000 以監看透過網路撥打的電話。

    Networking tab in Chrome that shows network activity

  7. 選取 [新增主圖] 按鈕以新增主圖。 輸入識別碼 "999"、名稱 "Fred" 和招呼語 "Hello",然後選取 [儲存]。 您應會在 [網路] 索引標籤中看到您已針對新 Hero 傳送 POST 要求。

    Networking tab in Chrome that shows network activity for Get and Post functions

    現在返回,並將 Post 和 Delete 函式新增至應用程式。

新增 Put 和 Delete 函式

  1. routes.js 中,在 post 路由器之後新增 putdelete 路由器。

    router.put('/hero/:uid', (req, res) => {
      heroService.putHero(req, res);
    });
    
    router.delete('/hero/:uid', (req, res) => {
      heroService.deleteHero(req, res);
    });
    
  2. 將下列程式碼複製到 hero.service.js 中的 checkServerError 函式之後。 此程式碼:

    • 建立 putdelete 函式
    • 執行是否找到 Hero 的檢查
    • 執行錯誤處理
    function putHero(req, res) {
      const originalHero = {
        uid: parseInt(req.params.uid, 10),
        name: req.body.name,
        saying: req.body.saying
      };
      Hero.findOne({ uid: originalHero.uid }, (error, hero) => {
        if (checkServerError(res, error)) return;
        if (!checkFound(res, hero)) return;
    
       hero.name = originalHero.name;
        hero.saying = originalHero.saying;
        hero.save(error => {
          if (checkServerError(res, error)) return;
          res.status(200).json(hero);
          console.log('Hero updated successfully!');
        });
      });
    }
    
    function deleteHero(req, res) {
      const uid = parseInt(req.params.uid, 10);
      Hero.findOneAndRemove({ uid: uid })
        .then(hero => {
          if (!checkFound(res, hero)) return;
          res.status(200).json(hero);
          console.log('Hero deleted successfully!');
        })
        .catch(error => {
          if (checkServerError(res, error)) return;
        });
    }
    
    function checkFound(res, hero) {
      if (!hero) {
        res.status(404).send('Hero not found.');
        return;
      }
      return hero;
    }
    
  3. hero.service.js 中,匯出新模組:

    module.exports = {
      getHeroes,
      postHero,
      putHero,
      deleteHero
    };
    
  4. 既然我們已更新程式碼,請選取 Visual Studio Code 中的 [重新啟動] 按鈕

  5. 重新整理網際網路瀏覽器中的頁面,然後選取 [新增主圖] 按鈕。 新增識別碼為 "9"、名稱為 "Starlord" 的 Hero,且招呼語為 "Hi"。 選取 [儲存] 按鈕以儲存新的主圖。

  6. 現在,選取 Starlord 主圖,並將招呼語從 "Hi" 變更為 "Bye",然後選取 [儲存] 按鈕。

    您現在可以在 [網路] 索引標籤中選取識別碼來顯示承載。 您可以在承載中看到招呼語現在已設定為 "Bye"。

    Heroes app and Networking tab showing the payload

    您也可以在 UI 中刪除其中一個 Hero,並查看完成刪除作業所需的時間。 試著針對名為 "Fred" 的主圖選取 [刪除] 按鈕。

    Heroes app and the Networking tab showing the time to complete the functions

    如果您重新整理頁面,[網路] 索引標籤會顯示取得 Hero 所需的時間。 雖然時間迅速,但大部分取決於您的資料所在的地理位置,以及在接近使用者的區域中異動複寫資料的能力。 您可以在接下來 (即將發行) 的教學課程中,進一步了解異地複寫。

下一步

在本教學課程中,您已完成下列作業:

  • 已將 Post、Put 和 Delete 函式新增至應用程式

稍後返回查看本教學課程系列中的其他影片。

正在嘗試為遷移至 Azure Cosmos DB 進行容量規劃嗎? 您可以使用現有資料庫叢集的相關資訊進行容量規劃。