How to use custom provider inside model's hook

Hi,

I am trying to use custom provider inside model’s hook. Here is an example

const Model = use('Model')
const MyProvider = use('MyProvider')

class MyModel extends Model {
   this.addHook('afterCreate', async (instance) => {
      console.log(MyProvider) // returns the Config object
      MyProvider.executeMyMethod(instance.property) // => returns error: MyProvider.executeMyMethod is not a function
   }
}

Here is how I register my provider:

const { ServiceProvider } = require('@adonisjs/fold')

class MyProvider extends ServiceProvider {
  register () {
    this.app.singleton('MyProvider', () => {
      const Config = this.app.use('Adonis/Src/Config')
      return new (require('.'))(Config)
    })
  }
}

module.exports = MyProvider

Here is the provider:

class MyProvider {
   executeMyMethod(property) {
      console.log(property)
   }
}
module.exports = MyProvider
1 Like

Hi

If you are calling a method on a class and not an instance of a class must you declare it as static.

class MyProvider {
   static executeMyMethod(property) {
      console.log(property)
   }
}
module.exports = MyProvider
2 Likes

Hi,

I’ve already figured it out. Thank you for your answer anyway.

1 Like