loopback : deleted column in model instead of actual delete

Viewed 403

I'm considering using Loopback to build a RESTFull API, internal usage. I'm currently prototyping a small portion of the API to evaluate limitations and workload. I have a huge constraint : I'm allowed to Create/Read/Update, but to Delete, I have update the DB entry to mark it as 'deleted' (boolean in the database). I'm not allowed to physically deleted the DB entry.

I have a PersistedModel, and some relation between object (dependencies, like one object child from another).

My question is : Is there a way to override the DELETE actions done in the background and input some custom code :

  • mark the object as "deleted" (like an UPDATE table SET deleted = 1 WHERE id = XXX)
  • manually CASCADE to dependent objects

while using the DELETE api call ?

Thanks fro your advice.

1 Answers

To overwrite delete method you can use the next code. Create a mixin based on it and attach for every required model

module.exports = function(Model) {

  Model.removeById = Model.deleteById = Model.destroyById = function(id, options, cb) {
    if (cb === undefined) {
      if (typeof options === 'function') {
        // destroyById(id, cb)
        cb = options;
      }
    }
    cb = cb || createPromiseCallback();

    Model.update({id: id, {deleted: true}, options, cb})
    return cb.promise;
  };
}
Related