问题
I have a patch endpoint in my REST API where every body parameter is optional. What is the best way of implementing it without checking each parameter manually?
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:
Use methods in the helpers namespace:
static declarations
const optional = name => ({name, skip: col => !col.exists});
const cs = new pgp.helpers.ColumnSet([
optional('title'),
optional('description'),
optional('value')
], {table: 'tasks'});
generating the query and executing it:
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);
});
In addition, you might want to use option emptyUpdate
of method helpers.update, to check that at least one column is being set, to avoid invalid query generation request and an error thrown.
来源:https://stackoverflow.com/questions/46817396/dynamic-named-parameters-in-pg-promise