Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SailsJS Soft Delete
// api/controllers/DestroyController.js
module.exports = {
Destroy: function (req, res) {
var model = sails.models[req.params.model];
model.softDelete({id: req.params.id}, function (data, err) {
if (err) {
return res.serverError(err);
}
return res.send(data);
});
}
};
// api/policies/softDeletes
module.exports = function (req, res, next) {
if(!req.options.model)
{
next();
}
else
{
// to only return non-deleted rows.
if(!req.options.where) req.options.where = {};
req.options.where.deletedAt = null;
next();
}
};
// config/models.js
var moment = require('moment'),
async = require('async');
module.exports.models = {
schema: true,
attributes: {
createdAt: 'datetime',
updatedAt: 'datetime',
deletedAt: 'datetime'
},
//softdeletes yay
softDelete: function(criteria, cb){
var processed = [];
this.find(criteria).then(function(rows){
if(rows.length == 1)
{
var row = rows.pop();
row.deletedAt = moment().format("YYYY-MM-DD HH:mm:ss");
row.save(function(err, row){
if(err){ cb(null, err) }
cb(row)
});
}
else
{
var errorSet = false;
async.eachLimit(rows, 1, function(row, nextRow){
row.deletedAt = moment().format("YYYY-MM-DD HH:mm:ss");
if(errorSet)
{
nextRow();
}
else
{
row.save(function(err, row){
if(err){
errorSet = err;
}
else
{
processed.push(row);
}
nextRow();
});
}
}, function(err){
if(err || errorSet)
{
cb(null, err ? err : errorSet)
}
else
{
cb(processed)
}
});
}
});
}
};
// config/policies.js
module.exports.policies = {
'*': ['softDeletes']
}
// config/routes.js
module.exports.routes = {
//overwrite destroy
'DELETE /:model/:id' : 'DestroyController.Destroy',
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.