skip update columns with pg-promise

前端 未结 3 1360
余生分开走
余生分开走 2020-12-21 12:38

I\'ve got an API up on node using pg-promise for Postgres, this works well but i\'m thinking about how to modify the PUT statement to handle NULLS in the input a little bett

3条回答
  •  独厮守ぢ
    2020-12-21 13:11

    Thank you @vitaly-t! faster and cleaner, always a good result :)

    for reference, i've also included the insert statement using the helpers as described above as well.

        //firstly create a function that skips the nulls for strings
    function str(column) {
        return {
            name: column,
            skip: c => c.value === null || c.value === undefined || !c.exists
        };
    }
    
    //now a function that skips nulls for integers, while parsing type
    function int(column) {
        return {
            name: column,
            skip: c => c.value === null || c.value === undefined || !c.exists,
            init: c => +c.value
        };
    }
    
    //creating a column set for all updates
    var usefulColumSet = new pgp.helpers.ColumnSet([
        str('string1'), str('string2'), str('string3'), str('string4'), str('string5'),
        str('string6'), int('integer1'), int('integer2'), int('integer3'),
        str('date1'), str('date2'), str('date3'), int('currency1'), int('currency2')
    ], {table: 'generic1'});
    
    //*********************CREATE a single record*************************
    function createRecord(req, res, next) {
        var insert = pgp.helpers.insert(req.body, usefulColumSet);
    
        db.none(insert)
            .then(function(){
                res.status(200)
                    .json({
                        status: 'success',
                        message: 'Inserted one record successully'
                    });
            })
            .catch(function(err){
                return next(err);
            });
    }
    
    
    //************************UPDATE a single record*************
    function updateRecord(req, res, next) {
        var update = pgp.helpers.update(req.body, usefulColumSet) + ' WHERE id = ' + parseInt(req.params.id);
    
        db.none(update)
            .then(function() {
                res.status(200)
                    .json({
                        status: 200,
                        message: 'updated a single record cleanly'
                    });
            })
            .catch(function(err) {
                return next(err);
            });
    }
    

提交回复
热议问题