pg-promise 中的动态命名参数

Dynamic named parameters in pg-promise

我的 REST API 中有一个补丁端点,其中每个正文参数都是可选的。在不手动检查每个参数的情况下实现它的最佳方法是什么?

db.none("update tasks set title=, description=, value= where id=",
    [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);
    });

使用 helpers 命名空间中的方法:

静态声明

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 来检查是否至少设置了一列,以避免无效的查询生成请求和抛出错误。