hookable.ts 787 B

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