Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 4x | /* eslint-disable no-useless-catch */ /** * @module Middleware * Middleware */ class Middleware { /** * @property {Array} middlewares - посилання на ланцюжок оброблення повідомлень */ #middlewares; /** * @property {function} callback - обробник повідомлень за замовченням */ #callback; /** * створює екземпляр масива посилань на ланцюжок оброблення повідомлень * @param {function} callback - обробник повідомлень * */ constructor(callback) { this.#middlewares = []; this.#callback = callback; if (callback) { this.#middlewares.push(callback); } } /** * додає обробник до ланцюжка оброблення повідомлень * @param {function} callback - обробник повідомлень * */ use(callback) { if (this.#callback) this.#middlewares.pop(); this.#middlewares = [ ...this.#middlewares, ...(Array.isArray(callback) ? callback : [callback]), ]; if (this.#callback) this.#middlewares.push(this.#callback); return this; } /** * виконуе ланцюжщк оброблення повідомлень * */ async execute(...args) { try { const res = args; const nextStatus = { status: true }; let index = 0; let error = null; while (nextStatus.status) { nextStatus.status = false; try { if (this.#middlewares[index]) await this.#middlewares[index](error, ...res, () => { nextStatus.status = true; }); } catch (e) { error = e; nextStatus.status = true; } index++; } return res; } catch (e) { throw e; } } } module.exports = Middleware; |