Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loopback beforeRemote for PUT requests

Using Loopback framework, I want to perform some operations before the Item is edited hence I am trying this but unable to bind this to the update hook.

  Item.beforeRemote("update", function(ctx,myitem,next) {
   console.log("inside update");
  });

Instead of update I have tried with updateAttributes,updateById, create but none works. This kind of beforeRemote hook works well with create on POST, but unable to get it with PUT during edit. The last solution left with me is again inspect the methodString with wildcard hook but I want to know if there is anything documented which I could not find.

Item.beforeRemote("**",function(ctx,instance,next){
  console.log("inside update");
});
like image 997
Swapnil Gondkar Avatar asked Dec 17 '15 04:12

Swapnil Gondkar


2 Answers

I know that two year have passed since this post was opened, but if any body have the same question and if you use the endpoint your_model/{id} the afterRemote hook is replaceById. If you need to know which method is fired in remote hook use this code:

yourModel.beforeRemote('**', function(ctx, unused, next) {
    console.info('Method name: ', ctx.method.name);
    next();
});
like image 126
Diego Alberto Zapata Häntsch Avatar answered Oct 03 '22 18:10

Diego Alberto Zapata Häntsch


Contrary to the comments, save is a remote hook, not an operation hook, but you want to use it as: prototype.save. The relevant operational hook would be before save. You can see a table of these on the LoopBack docs page. I would probably implement this as an operational hook though, and use the isNewInstance property on the context to only perform the action on update:

Item.observe('before save', function(ctx, next) {
  if (ctx.isNewInstance) {
    // do something with ctx.currentInstance
  }
  next();
});
like image 33
Jordan Kasper Avatar answered Oct 03 '22 17:10

Jordan Kasper