Swapnil Gondkar
Swapnil Gondkar

Reputation: 345

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");
});

Upvotes: 5

Views: 3118

Answers (5)

Samir S
Samir S

Reputation: 1

On loopback3 for PATCH you can use "prototype.patchAttributes" to sanitize your data before the update.

YourModel.beforeRemote('prototype.patchAttributes', (ctx, unused, next) => { 
  console.log(ctx.args.data);
  next();
});

Upvotes: 0

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();
});

Upvotes: 7

cuddlemeister
cuddlemeister

Reputation: 1785

Came here looking for another thing, guess it will be helpful to someone. For before remote model/:id patch method you have to use "prototype.patchAttributes".

Upvotes: 3

Anil Jangra
Anil Jangra

Reputation: 101

Sorry for bumping into old question but its for those who are still searching.

'prototype.updateAttributes' can be used as remote hook for update requests. and @jakerella , there is no remote hook called 'save' , i myself tried it, but didnt work.

Upvotes: 3

Jordan Kasper
Jordan Kasper

Reputation: 13273

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();
});

Upvotes: 5

Related Questions