node.js - 实现 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");
}
};
解决方案
我建议使用COALESCE
. 你可以像这样使用它:
UPDATE users SET host = COALESCE($2, host), updated_on = NOW() WHERE...
如果提供了,这将覆盖host
数据库中的值。如果不是,则保留当前分配的值。