Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip delete operation in loopback, send custom response object

I want to overwrite the default delete operations in strongloop and replace them by some kind of "soft delete" which just sets a flag to deleted. I got it so far, that I hooked the original operation and without calling the next() function the operation ist not permitted to data base. But it's also not sending any response state. So what's the best way to do this or to send custom response object?

module.exports = function (Module) {
  Module.observe('before delete', function(ctx, next) {
    id = ctx.where['id'];
    Module.update({id: id}, {deleted: true}, null);
    //next(); // don't call next to avoid deleting
  }); 

Update: not a solution but at least it triggers some response for the API:

Module.observe('before delete', function(ctx, next) {
    var id = ctx.where['id'];
    Module.update({id: id}, {deleted: true}, null);

    // dirty method to trigger response
    var err = new Error();  // create new error object
    err.statusCode = 204;   // set response code to empty response
    next(err);

  });
like image 707
Karl Adler Avatar asked May 16 '26 15:05

Karl Adler


1 Answers

EDIT Here's the correct answer:

module.exports = function(Model) {
  let app;
  Model.once('attached', (a) => {
    app = a;

    const deleteById = Model.deleteById;

    Model.deleteById = (id, options, cb) => {
      Model.updateAll({id: id}, {
        deletedAt: new Date(),
        deletedBy: options.accessToken.userId,
      });
      cb(null,'deleted')
    };

    // ...
  });
}

In LB2 and LB3, one approach is to use operation hooks. In the concerned model.js file add this:

module.exports = function(Model) {
  let app;
  Model.once('attached', (a) => {
    app = a;
    Model.observe('before delete', (ctx, next) => {
      Model.findById(ctx.where.id, (err, instance) => {
        if (err) {
          return next(err);
        }
        instance.deletedAt = new Date();

        // ...
        // other modifications to instance
        // ...

        // save this in the hookState to retrieve it in after delete hook
        ctx.hookState.deletedModelInstance = instance;
        next();
      });
    });

    Model.observe('after delete', (ctx, next) => {
      Model.replaceOrCreate(ctx.hookState.deletedModelInstance,
        (err, instance) => {
          if (err) {
            console.log(
              'An error occured while restoring data ' +
              'from hookState after delete operation'
            );
          }
        next();
      });
    });
  });
}
like image 153
Prashant Avatar answered May 18 '26 03:05

Prashant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!