Dynamic named parameters in pg-promise

橙三吉。 提交于 2019-12-23 02:18:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!