Search code examples
javascriptnode.jsfeathersjsfeathers-hookfeathers-service

How to avoid service multiple time run in hook using feathers.js?


I'm facing problem in feathers service in feathers hook. Exactly the problem is i'm using feather service in feather hook and when i call service in hook it run multiple times so that memory issue is to be happen. my question is how to avoid service multiple run in hook.

function orders(hook){
  return new Promise((resolve,reject) =>{
      hook.app.service('orders')
        .find(hook.app.query)
        .then(result => {
          resolve(result.data)
        }).catch(e =>{
        reject(e)
      })
  })
}

my expected solution is the service should be run in single time at hook.


Solution

  • A service method ideally shouldn't call itself in a hook but if you do, you will need a breaking condition so that it doesn't keep calling itself in an infinite loop. This can be done by e.g. passing a parameter that will skip the self-referential call if it is not set:

    app.service('myservice').hooks({
      before: {
        find(hook) {
          if(!hook.params.fromOtherHook) {
    
            const newParams = Object.assign({
              fromOtherHook: true
            }, hook.params);
    
            return hook.service.find(newParams);
          }
        }
      }
    });