使用用于 MongoDB 的 Azure Cosmos DB API 创建 Angular 应用 - 将 CRUD 函数添加到应用

适用对象: Mongodb

重要

你是否正在寻找一种数据库解决方案,以应对需要高扩展性、99.999% 可用性服务级别协议(SLA)、即时自动扩展和跨多个区域的自动故障转移的场景? 请考虑使用 Azure Cosmos DB for NoSQL。

本教程包含多个部分,演示了如何通过 Express 和 Angular 创建以 Node.js 编写的新应用,然后将其连接到使用 Azure Cosmos DB 的 API for MongoDB 配置的 Azure Cosmos DB 帐户。 本教程的第 6 部分基于第 5 部分,涵盖以下任务:

  • 为 hero 服务创建 Post、Put 和 Delete 函数
  • 运行应用

先决条件

在开始本教程的这一部分之前,请完成本教程的第 5 部分 中的步骤。

小窍门

本教程介绍生成应用程序的各个步骤。 若要下载完成的项目,可从 GitHub 上的 angular-cosmosdb 存储库获取完成的应用程序。

向 hero 服务添加 Post 函数

  1. 在 Visual Studio Code 中,按“拆分编辑器”按钮来并排打开 routes.js 和 hero.service.js。

    请注意,routes.js第 7 行在 hero.service.js第 5 行调用getHeroes函数。 你需要为 POST、PUT 和 DELETE 函数创建同样的配对关系。

    Visual Studio Code 中的 routes.js 和 hero.service.js

    让我们首先对 hero 服务进行编码。

  2. 将以下代码复制到 hero.service.js 中 getHeroes 函数之后 module.exports 之前。 此代码:

    • 使用英雄模型发布新英雄。
    • 查看响应,了解是否存在错误,然后返回状态值 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 中的 路由器之后为 post 函数添加一个路由器。 此路由器一次发布一个hero。 以这种方式构建路由器文件可清晰地显示所有可用的 API 终结点,并将实际工作留给 hero.service.js 文件。

    router.post('/hero', (req, res) => {
      heroService.postHero(req, res);
    });
    
  5. 运行应用,看是否一切正常。 在Visual Studio Code中,保存所有更改,选择左侧的“调试”按钮,然后选择“开始调试”按钮。

  6. 返回到 Internet 浏览器,在大多数计算机上按 F12 打开“开发人员工具网络”选项卡。 转到 http://localhost:3000 以查看通过网络进行的调用。

    Chrome 中的“网络”选项卡,显示网络活动

  7. 通过选择“添加新英雄”按钮添加新的英雄。 输入 ID 为“999”,名称为“Fred”,并说出“Hello”,然后选择“ 保存”。 你应该在“网络”选项卡中看到你为新英雄发送了 POST 请求。

    Chrome 中的“网络”选项卡,显示 Get 和 Post 函数的网络活动

    接下来,返回并向应用添加 Put 和 Delete 函数。

添加 Put 和 Delete 函数

  1. 在 routes.js 中的 post 路由之后添加 put 和 delete 路由。

    router.put('/hero/:uid', (req, res) => {
      heroService.putHero(req, res);
    });
    
    router.delete('/hero/:uid', (req, res) => {
      heroService.deleteHero(req, res);
    });
    
  2. 将以下代码复制到 hero.service.js 中 函数之后。 此代码:

    • 创建 put 和 delete 函数
      • 检查是否已找到英雄
      • 处理错误
    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. 刷新 Web 浏览器中的页面,然后选择“ 添加新英雄 ”按钮。 添加一个新的英雄,ID 为“9”,名称为“Starlord”,口头禅为“Hi”。 选择“保存”按钮保存新的英雄。

  6. 现在请选择“Starlord”英雄,并将“saying”从“Hi”更改为“Bye”,然后选择“Save”按钮。

    现在可以在“网络”选项卡中选择 ID 来显示有效负载了。 你可以在负载中看到,该文本现已设置为“Bye”。

    Heroes 应用的“网络”选项卡,显示有效负载

    还可以在 UI 中删除某个 hero,看完成删除操作需要多少时间。 通过为名为“Fred”的英雄选择“ 删除 ”按钮来尝试此操作。

    Heroes 应用和“网络”选项卡,显示完成函数操作的时间

    如果刷新页面,“网络”选项卡会显示获取英雄所需的耗时。 尽管速度很快,但很大程度上取决于数据在中国的位置,以及您是否能够在靠近用户的区域进行地理复制。 可以在即将推出的下一教程中详细了解异地复制。

后续步骤

在本教程的这一部分中,你已完成以下任务:

  • 向应用添加 Post、Put 和 Delete 函数

在本教程系列中查找其他视频。

尝试为迁移到 Azure Cosmos DB 进行容量规划? 可以使用有关现有数据库群集的信息进行容量规划。

  • 如果仅知道现有数据库群集中的 vcore 数和服务器数,请阅读有关 使用 vCore 或 vCPU 估算请求单位的信息。
  • 如果知道当前数据库工作负载的典型请求速率,请阅读有关使用 Azure Cosmos DB 容量规划工具估计请求单位的信息。