Search code examples
node.jsloopbackjsstrongloop

Operation hook for hasAndBelongsToMany


How can I configure an operation hook, such as after save, when linking or unlinking an instance of the foreign model?

Using loopback's example Assembly and Part model: https://docs.strongloop.com/display/public/LB/HasAndBelongsToMany+relations

I would like to execute code when adding (or removing) a part to an assembly through PUT /assembly/{assembly_id}/parts/rel/{part_id}


Solution

  • I was afraid I would have to lose the magical 'hasAndBelongsToMany' and be forced to use hasManyThrough.

    But, turns out you can define your methods in the defined models (Assembly and Part)

    Assembly.afterRemote('*.__link__parts', function(context, instance, next){
        console.log(instance);
        next();
    });
    
    Assembly.afterRemote('*.__unlink__parts', function(context, instance, next){
        console.log(instance);
        next();
    });