使更新 API 动态化

making update API dynamic

小问题,我怎样才能使这个 API 仅从我的请求中获取定义 json 键,而不使用 if statement 检查我请求中的每个键,如下所示:

const updateArticle = async (req, res) => {
  const { title, description, body } = req.body;
  try {
    const article = await Article.findByPk(req.params.id);

    if (title) article.title = title;
    if (description) article.description = description;
    if (body) article.body = body;

    await article.save();

    res.json("Article updated.");
  } catch (err) {
    console.log(err);
  }
};

您可以使用 Object.assign() 方法将 source 对象的属性覆盖到 target 对象。

const updateArticle = async (req, res) => {
  const { title, description, body } = req.body;
  try {
    const article = await Article.findByPk(req.params.id);

    Object.assign(article, req.body);

    await article.save();

    res.json("Article updated.");
  } catch (err) {
    console.log(err);
  }
};