|
| 1 | +/* eslint-disable no-console */ |
| 2 | +/* eslint-disable no-unused-vars */ |
| 3 | +/* eslint-disable no-param-reassign */ |
| 4 | +const querify = require('querystring').stringify; |
| 5 | +const onFinished = require('on-finished'); |
| 6 | +const template = require('./src/templates/default'); |
| 7 | +const sendMessage = require('./src/sendMessage'); |
| 8 | +const { printWarning } = require('./src/utils/print'); |
| 9 | + |
| 10 | +/** |
| 11 | + * @param options Middleware's options |
| 12 | + * @param options.botToken Bot's token, sent by BotFather |
| 13 | + * @param options.chatId ChatID of a Telegram chat to send notifications to |
| 14 | + */ |
| 15 | +const telegramMiddleware = (options) => (req, res, next) => { |
| 16 | + if (!options) options = {}; |
| 17 | + const { botToken } = options; |
| 18 | + const { chatId } = options; |
| 19 | + |
| 20 | + if (!botToken) printWarning('botToken not provided, errors get ignored'); |
| 21 | + if (!chatId) printWarning('chatId not provided, errors get ignored'); |
| 22 | + |
| 23 | + if (botToken && chatId) { |
| 24 | + onFinished(res, (err, _) => { |
| 25 | + if (err || res.statusCode >= 400) { |
| 26 | + const text = template(req, res, options); |
| 27 | + |
| 28 | + let query = { |
| 29 | + text, |
| 30 | + chat_id: chatId, |
| 31 | + parse_mode: 'Markdown', |
| 32 | + }; |
| 33 | + |
| 34 | + // If statusCode is less than 500, then this error is not critical, we disable notification |
| 35 | + if (res.statusCode < 500) query.disable_notification = true; |
| 36 | + |
| 37 | + query = querify(query); |
| 38 | + |
| 39 | + try { |
| 40 | + sendMessage(botToken, query); |
| 41 | + } catch (e) { |
| 42 | + console.log(e); |
| 43 | + next(e); |
| 44 | + } |
| 45 | + } |
| 46 | + }); |
| 47 | + } |
| 48 | + next(); |
| 49 | +}; |
| 50 | + |
| 51 | +module.exports = telegramMiddleware; |
0 commit comments