Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Soft delete in Sails/Waterline

Trying to delete a user model using:

//Hard Delete    
User.destroy({id:userId}, function(err, res){  
  //Hard Delete
})  

I need to do a soft delete on User model and currently setting a flag isDeleted to true on delete and updating document:

updateUser.isDeleted = true;
User.update({id:userId}, updateUser, function(err, res){
  Update project
})

and while fetching documents I am doing a check If isDeleted - true or not.
Is there any In-built feature provided by Sails or Waterline which I can configure to perform a soft delete and avoid updating and then fetching based on isDeleted flag?

like image 877
Abhishek Avatar asked Nov 09 '22 22:11

Abhishek


1 Answers

you can use beforeFind() life cycle function for filter of soft deleted records

model: parrot,js

module.exports = {
    attributes: {
        // e.g., "Polly"
        name: {
            type: 'string'
        },

        // e.g., 3.26
        wingspan: {
            type: 'float',
            required: true
        },

        // e.g., "cm"
        wingspanUnits: {
            type: 'string',
            enum: ['cm', 'in', 'm', 'mm'],
            defaultsTo: 'cm'
        },

        // e.g., [{...}, {...}, ...]
        knownDialects: {
          collection: 'Dialect'
        },

        isDeleted:{
            type:'boolean'
        }
    },

    beforeFind: function(values, cb) {
        values.isDeleted = false;
        cb();
    }
}

ParrotController.js

module.exports = {

    // getting default parrots isDeleted = true
    list: function (req, res) {

        Parrot
        .find()
        .exec(function(err, parrots) {
            if(err) return res.send({ flag:false, data:[], message:"Error." });

            if(parrots && parrots.length){
                return res.send({ flag:true, data:parrots, message:"Success." });
            }
            else{
                return res.send({ flag:false, data:[], message:"Parrot list is empty." });
            }

        });

    }
};
like image 81
Arjun Kava Avatar answered Nov 15 '22 06:11

Arjun Kava