interceptorManager.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const debug = require('debug')('crowi:InterceptorManager')
  2. /**
  3. * the manager class of Interceptor
  4. */
  5. class InterceptorManager {
  6. constructor(crowi) {
  7. this.interceptors = [];
  8. }
  9. addInterceptor(interceptor) {
  10. this.addInterceptors([interceptor]);
  11. }
  12. addInterceptors(interceptors) {
  13. this.interceptors = this.interceptors.concat(interceptors);
  14. }
  15. process(contextName, ...args) {
  16. // filter only context matches
  17. const matchInterceptors = this.interceptors.filter((i) => i.isInterceptWhen(contextName));
  18. const parallels = matchInterceptors.filter((i) => i.isProcessableParallel());
  19. const sequentials = matchInterceptors.filter((i) => !i.isProcessableParallel());
  20. debug(`processing parallels(${parallels.length})`);
  21. debug(`processing sequentials(${sequentials.length})`);
  22. return Promise.all(
  23. parallels.map((interceptor) => {
  24. return interceptor.process(contextName, ...args);
  25. })
  26. .concat([
  27. sequentials.reduce((prevPromise, nextInterceptor) => {
  28. return prevPromise.then((...results) => nextInterceptor.process(contextName, ...results));
  29. }, Promise.resolve(...args))
  30. ])
  31. ).then(() => {
  32. console.log("Promise.all().then()");
  33. return;
  34. });
  35. }
  36. }
  37. module.exports = (crowi) => {
  38. return new InterceptorManager(crowi);
  39. }