interceptorManager.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. /**
  10. * add an Interceptor
  11. * @param {BasicInterceptor} interceptor
  12. */
  13. addInterceptor(interceptor) {
  14. this.addInterceptors([interceptor]);
  15. }
  16. /**
  17. * add Interceptors
  18. * @param {BasicInterceptor[]} interceptors
  19. */
  20. addInterceptors(interceptors) {
  21. const interceptorIds = interceptors.map((i) => i.getId());
  22. debug(`adding interceptors '${interceptorIds}'`);
  23. this.interceptors = this.interceptors.concat(interceptors);
  24. }
  25. /**
  26. * process Interceptors
  27. *
  28. * @param {string} contextName
  29. * @param {any} args
  30. */
  31. process(contextName, ...args) {
  32. debug(`processing the context '${contextName}'`);
  33. // filter only contexts matches to specified 'contextName'
  34. const matchInterceptors = this.interceptors.filter((i) => i.isInterceptWhen(contextName));
  35. const parallels = matchInterceptors.filter((i) => i.isProcessableParallel());
  36. const sequentials = matchInterceptors.filter((i) => !i.isProcessableParallel());
  37. debug(`${parallels.length} parallel interceptors found.`);
  38. debug(`${sequentials.length} sequencial interceptors found.`);
  39. return Promise.all(
  40. // parallel
  41. parallels.map((interceptor) => {
  42. return this.doProcess(interceptor, contextName, ...args);
  43. })
  44. // sequential
  45. .concat([
  46. sequentials.reduce((prevPromise, nextInterceptor) => {
  47. return prevPromise.then((...results) => this.doProcess(nextInterceptor, contextName, ...results));
  48. }, Promise.resolve(...args)/* initial Promise */)
  49. ])
  50. ).then(() => {
  51. debug(`end processing the context '${contextName}'`);
  52. return;
  53. });
  54. }
  55. doProcess(interceptor, contextName, ...args) {
  56. return interceptor.process(contextName, ...args)
  57. .then((...results) => {
  58. debug(`processing '${interceptor.getId()}' in the context '${contextName}'`);
  59. return Promise.resolve(...results);
  60. })
  61. .catch((reason) => {
  62. debug(`failed when processing '${interceptor.getId()}' in the context '${contextName}'`);
  63. debug(reason);
  64. return Promise.resolve(...args);
  65. });
  66. }
  67. }
  68. module.exports = (crowi) => {
  69. return new InterceptorManager(crowi);
  70. }