interceptorManager.js 2.2 KB

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