Search code examples
loopbackjsstrongloop

Operation hooks or remote hooks for create method


I have a simple question. Whats the main difference doing a MyModel.beforeRemote('create') hook for a create method and a MyModel.observe('before save'). I already read the docs and I know that operation hooks are not tied to a particular method, but rather are triggered from all methods that execute a particular high-level operation (ex. create). But in this particular example, MyModel.beforeRemote('create') will work as same as I do MyModel.observe('before save'), right? Or this will execute on other "state" of the api flow?

Remote hook:

MyModel.beforeRemote('create', (ctx, next) => {
  console.log("beforeRemote");
  next();
}

Operation hook:

MyModel.observe('before save', (ctx, next) => {
  console.log("before save");
  next();
}

Solution

  • MyModel.beforeRemote('create') would only be invoked for the 'create' remote method, but MyModel.observe('before save') would be invoked for any of these:

    • create
    • upsert
    • findOrCreate
    • updateAll
    • prototype.save
    • prototype.updateAttributes

    See the table here for all the remote methods that would invoke each operation hook: https://docs.strongloop.com/display/APIC/Operation+hooks