pg-promise中的动态命名参数

时间:2017-10-18 19:02:34

标签: node.js pg-promise

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

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);
    });

1 个答案:

答案 0 :(得分:1)

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

相关问题