hookable.ts 853 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { UrlArgs } from '~/types/interfaces'
  2. import BaseHook from '~/services/data/hooks/baseHook'
  3. /**
  4. * Base class for an object which support hooks
  5. */
  6. abstract class Hookable {
  7. protected hooks: Array<typeof BaseHook> = []; // how could we replace 'any'?
  8. /**
  9. * Iterate over the available hooks and invoke the ones
  10. * that support the given args
  11. */
  12. protected async triggerHooks (args: UrlArgs) {
  13. for (const Hook of this.sortedHooks()) {
  14. if (Hook.support(args)) {
  15. await new Hook().invoke(args)
  16. }
  17. }
  18. }
  19. /**
  20. * Sort the available hooks by priority
  21. * @private
  22. */
  23. private sortedHooks (): Iterable<any> {
  24. return this.hooks.sort(function (a, b) {
  25. if (a.priority > b.priority) { return 1 }
  26. if (a.priority < b.priority) { return -1 }
  27. return 0
  28. })
  29. }
  30. }
  31. export default Hookable