优化API中的SQL事务
P粉343408929
P粉343408929 2023-08-18 13:24:59
[JavaScript讨论组]
<p>最近我参加了一次工作面试,然后我得到了一点作业。然后我收到了反馈,说我的更新端点中有不必要的查询和事务组合。</p> <pre class="brush:php;toolbar:false;">export const update = async (req: Request, res: Response, next: NextFunction) =&gt; { try { const reportId = parseInt(req.params.id) const { name, age, info } = req.body const report = await ReportModel.findOne({ where: { id: reportId } }) if (!report) return next(new EntityNotExistError(&quot;报告不存在&quot;)) await ReportModel.update({ name, age, info }, { where: { id: reportId } }) const _report = await ReportModel.findOne({ where: { id: reportId } }) return res.json({ message: &quot;报告编辑成功&quot;, report: _report }) } catch (error) { return next(error) } }</pre> <p>正如你所看到的,第一个查询检查实体是否存在,然后我对实体进行更新,最后一个查询返回更新后的实体。 有没有一些方法可以优化与数据库的通信?</p>
P粉343408929
P粉343408929

全部回复(1)
P粉201448898

您的代码涉及到对数据库的三个不同交互,用于单个更新操作:

  1. 检查实体是否存在 | 代码:ReportModel.findOne()
  2. 更新实体 | 代码:ReportModel.update()
  3. 获取更新后的实体,以便在响应中返回 | 代码:ReportModel.findOne()

减少数据库查询可以完成任务并提高性能。

**您修复后的代码:**

export const update = async(req: Request, res: Response, next: NextFunction) => {
  try {
    const reportId = parseInt(req.params.id);
    const {
      name,
      age,
      info
    } = req.body;

    // 执行更新并获取受影响的行数
    const [numberOfAffectedRows] = await ReportModel.update({
      name,
      age,
      info
    }, {
      where: {
        id: reportId
      },
      // 此标志检查更新函数是否返回更新后的对象
      returning: true
    });

    // 检查实体是否被找到和更新
    if (numberOfAffectedRows === 0) {
      return next(new EntityNotExistError("报告不存在"));
    }

    // 获取更新后的报告
    const updatedReport = await ReportModel.findOne({
      where: {
        id: reportId
      }
    });

    return res.json({
      message: "报告已成功编辑",
      report: updatedReport
    });

  } catch (error) {
    return next(error);
  }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号