pg-promise中的dynamic命名参数

我在我的REST API中有一个补丁端点,其中每个身体参数都是可选的。 没有手动检查每个参数,实现它的最好方法是什么?

db.none("update tasks set title=$1, description=$2, value=$3 where id=$4", [req.body.title, req.body.description, parseInt(req.body.value), req.params.id]) .then(function () { res.status(200) .json({ status: "success", message: "Updated task" }); }) .catch(function (err) { return next(err); }); 

在助手命名空间中使用方法:

静态声明

 const optional = name => ({name, skip: col => !col.exists}); const cs = new pgp.helpers.ColumnSet([ optional('title'), optional('description'), optional('value') ], {table: 'tasks'}); 

生成查询并执行它:

 const update = pgp.helpers.update(req.body, cs) + ' WHERE id = ' + req.params.id; db.none(update) .then(function () { res.status(200) .json({ status: "success", message: "Updated task" }); }) .catch(function (err) { return next(err); }); 

此外,您可能需要使用方法helpers.update的选项emptyUpdate来检查是否至less设置了一列,以避免无效的查询生成请求和抛出的错误。