代码之家  ›  专栏  ›  技术社区  ›  cksrc

pg-promise中的动态命名参数

  •  1
  • cksrc  · 技术社区  · 7 年前

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

    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 回复  |  直到 7 年前
        1
  •  1
  •   vitaly-t    7 年前

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

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