|
| 1 | +const co = require('co'); |
| 2 | + |
| 3 | +/** |
| 4 | + * Default context object to start with |
| 5 | + * |
| 6 | + * @type {{middlewares: Array}} |
| 7 | + */ |
| 8 | +const propertiesObject = { |
| 9 | + middlewares: [] |
| 10 | +}; |
| 11 | + |
| 12 | +function defaultMiddleware(msg) { |
| 13 | + this.msg = msg; |
| 14 | + this.shouldStop = false; |
| 15 | + |
| 16 | + this.stop = () => { |
| 17 | + this.shouldStop = true; |
| 18 | + }; |
| 19 | +} |
| 20 | + |
| 21 | +const botCallback = function botCallback() { |
| 22 | + const args = arguments; |
| 23 | + |
| 24 | + // Check if there is msg.chat.id so caller is message to bot |
| 25 | + if (!args.length) { |
| 26 | + console.error( |
| 27 | + '[node-telegram-bot-api-middleware]: No arguments passed ' + |
| 28 | + 'to a function used in bot event callback' |
| 29 | + ); |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + if (typeof args[0].chat === 'undefined') { |
| 34 | + console.error( |
| 35 | + '[node-telegram-bot-api-middleware]: Chat id not ' + |
| 36 | + 'defined in arguments. Not executing middlewares' |
| 37 | + ); |
| 38 | + |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + if (typeof args[0].chat.id === 'undefined') { |
| 43 | + console.error( |
| 44 | + '[node-telegram-bot-api-middleware]: There is no ' + |
| 45 | + 'visible chat id in chat in arguments. Not executing middlewares' |
| 46 | + ); |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + const context = { |
| 51 | + msg: args[0] |
| 52 | + }; |
| 53 | + |
| 54 | + this.middlewares.unshift(defaultMiddleware); |
| 55 | + |
| 56 | + return co(function* executeMiddlewares() { |
| 57 | + for (let i = 0, size = this.middlewares.length; i < size; i++) { |
| 58 | + if (context.shouldStop) { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + const middleware = co.wrap(this.middlewares[i]); |
| 63 | + |
| 64 | + yield middleware.apply(context, args); |
| 65 | + } |
| 66 | + }.bind(this)); |
| 67 | +}; |
| 68 | + |
| 69 | +function copyContextWithConcatenation(oldContext) { |
| 70 | + return { |
| 71 | + middlewares: oldContext.middlewares.slice() |
| 72 | + }; |
| 73 | +} |
| 74 | + |
| 75 | +/** |
| 76 | + * @param middleware |
| 77 | + * @returns {function(this:{middlewares})} |
| 78 | + */ |
| 79 | +const use = function use(middleware) { |
| 80 | + /** |
| 81 | + * @type {Object} [middlewares] |
| 82 | + */ |
| 83 | + const copy = copyContextWithConcatenation(this); |
| 84 | + |
| 85 | + copy.middlewares.push(middleware); |
| 86 | + |
| 87 | + const callback = botCallback.bind(copy); |
| 88 | + |
| 89 | + callback.use = use.bind(copy); |
| 90 | + |
| 91 | + return callback; |
| 92 | +}.bind(propertiesObject); |
| 93 | + |
| 94 | +exports.use = use; |
0 commit comments