loopback icon indicating copy to clipboard operation
loopback copied to clipboard

Unable to alter desired attribute value due to missing model instance in Access/Loaded Hook's context objects

Open kestrel97 opened this issue 7 years ago • 2 comments

I want to alter an attribute in someModel, whenever a find is called over this model. As I can't use remote Hooks as find is not a remote method, rather built in, and in operational hooks find/findOne only trigger access and loaded hooks, and as my research, they do not return the model instance in their ctx (or if they do, I would like to know where), I want to do something like:

modelName.observe('loaded', function (ctx, next) {
      ctx.someModel_instance.updateAttribute(someCount, value
            ,function(err, instance){
             if (err) next(err)
                else{
                      console.log("done")
                 }
                
      });


} 

kestrel97 avatar Jun 26 '19 08:06 kestrel97

Why can't you use operation hooks? See more at Operation Hooks

sujeshthekkepatt avatar Jun 26 '19 11:06 sujeshthekkepatt

Work Around: As loaded does not return model instance but it does return ctx.data, in which it returns a copy of the data in your model, If you happen to have a unique ID in your model so you can fetch model instance by findById and can persistently access/alter the attribute of the said model. e.g:

modelName.observe('loaded', function (ctx, next) {
        modelName.findOne({
          where: {id : ctx.data.id},
          },function(err, someModel_instance){
                    if (err) next(err)
                    else{   
                        someModel_instance.updateAttribute(someCount,value
                            , function(err, instance){
                                console.log(done)
                        });     
                        }
                });
                next();
} );

This will do the trick, but the problem will be non-stop recursion that it causes. As findOne and updateAttribute will trigger the loaded hook again and so on. This can be resolved by using ctx.options field which acts like an empty container and can be used to store flags. e.g:

modelName.observe('loaded', function (ctx, next) {
    if(ctx.options && !ctx.options.alreadyFound){

        modelName.findOne({
          where: {id : ctx.data.id},
          },{alreadyFound = true}, function(err, someModel_instance){
                    if (err) next(err)
                    else{   
                        someModel_instance.updateAttribute(someCount,value
                            ,{alreadyFound = true}, function(err, instance){
                                console.log(done)
                        });     
                        }
                });

    }
    next();
});

kestrel97 avatar Jun 27 '19 10:06 kestrel97