实现 PATCH API 端点的优雅方式?

埃德

我想部分更新我的用户对象,因为用户可以在创建用户后更新他们选择的任何属性。

例如,他们可以决定提供布尔主机值、dob 和/或电话号码,但这些属性是可选的。

检查以查看 PATCH 请求中提供了哪些字段并仅更新这些属性的最佳方法是什么?

用户架构:

CREATE TABLE users (
  id uuid PRIMARY KEY DEFAULT
  uuid_generate_v4(),
  first_name VARCHAR(255) NOT NULL,
  middle_name VARCHAR(255),
  last_name VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL,
  password VARCHAR(255) NOT NULL,
  created_on TIMESTAMPZ NOT NULL,
  host BOOLEAN NOT NULL DEFAULT FALSE, 
  updated_on TIMESTAMPZ,
  email_verified BOOLEAN NOT NULL DEFAULT FALSE,
  last_login TIMESTAMPZ,
  telephone VARCHAR(15),
  dob DATE,
);

用户更新控制器

const update = async (req, res, next) => {    
  try {
    //1. Destructure the req.body 
    const {host, telephone, dob} = req.body;

    //2. Enter the updated user attributes inside of database
    const updatedUser = await pool.query(
      "UPDATE users SET host = $2, updated_on = NOW() WHERE id = $1 RETURNING *", [
        req.user, host
      ]
    );

    res.status(200).json({message: 'Your profile has been successfully updated'});
  } 
  catch (err) {
    console.error(err.message);
    res.status(500).send("Server Error");  
  }
};
     
马特B

我建议使用COALESCE. 你可以像这样使用它:

UPDATE users SET host = COALESCE($2, host), updated_on = NOW() WHERE...

host如果提供,这将覆盖数据库中的值如果不是,则保留当前分配的值。

来源:https : //www.postgresqltutorial.com/postgresql-coalesce/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章