Search code examples
node.jsloopbackjsstrongloop

How to create hook in strongloop loopback for soft delete


I am expecting to create hook in Strongloop Loopback for all model for the purpose of achieving the soft delete.

I wish to include where filter automatically as deleted:0 so only non-deleted data is retrieved. I want same logic for validation, that automatically my query concatenate with deleted:0 condition. I want same for associations, so only related data is fetched.

To achieve so from DB side I have created a flag with default value 0. If I wish to fetch deleted records. I simply attach deleted:1 so it overrite base condition. Ang gives me relevant.

I am PHP Dev so to achive so in frameworks, I attach condition in beforeFilter in base model. Please help me here with Strongloop Loopback.


Solution

  • You can set a default scope on your models. This will be applied to all queries of that model. You can create a base model with that default scope and inherit that base model in the other models that you're implementing the soft delete on.

    {
      "name": "Base",
      "properties": {
        ...
      }
      "scope": {
        "order": "name",
        "limit": 100
        "where": {
          "deleted": 0
        }
      }
    }
    

    Then in the models you want use the default scope on you would add the Base model as a the base: property of the models that would use the soft-delete.

    {
      "name": "Product",
      "plural": "products",
      "base": "Base",
    ...
    }
    

    You can read more in their docs here: Default Scope in StrongLoop