Search code examples
node.jshookaccess-tokenloopbackjs

How to get the Access Token from a delete route in LoopBack 3


I'm trying to do some log work on delete routes; and I've crossed some difficulty in getting the Access Token in the 'before delete' hook, that is triggered when calling the destroyById method of the PersistentModel in LoopBack 3.

Is there any means to retrieve the access token in the 'before delete' hook? I've searched already within the context parameter of the hook function, and it's nowhere to be found (whereas it's there in POST or PUT routes).


Solution

  • As it happens, The 'before delete' hook also has the accessToken within its context, only when the hook is called directly because of the DELETE route of the associated model.

    Indeed, there is no accessToken if the the hook is called because of the PersistentModel method destroyById or destroyAll, which does not pass the context downwards to the 'before delete' hook.

    To get the access token from the context in a 'before save' or 'before delete' hook:

    const accessTokenId = ctx.options.accessToken.id;