2017-10-18 116 views
1

我的REST API中有一个补丁端点,其中每个身体参数都是可选的。无需手动检查每个参数,实现它的最佳方式是什么?pg-promise中的动态命名参数

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

您的查询包含4个参数,而您仅传入3个值。这看起来不正确。你需要先解决你的例子。 –

回答

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

+0

你能简单地解释一下,还是指向正确的方向,让我理解静态声明部分? – Shakur

+0

@Shakur静态 - 意味着你只声明一次。使用API​​和文档的所有类型的链接 - 我从一开始就给你。如果你想要更多的例子 - StackOverflow有很多,如果你搜索'pg-promise ColumnSet':https://stackoverflow.com/search?tab=votes&q=pg-promise%20ColumnSet –