UNPKG

@naturalcycles/nodejs-lib

Version:
108 lines 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const js_lib_1 = require("@naturalcycles/js-lib"); const __1 = require(".."); const __2 = require(".."); const colors_1 = require("../colors"); const { SLACK_WEBHOOK_URL } = process.env; /** * Use it in your top-level scripts like this: * * runScript(async () => { * await lalala() * // my script goes on.... * }) * * Advantages: * - Works kind of like top-level await * - No need to add `void` * - No need to add `.then(() => process.exit()` (e.g to close DB connections) * - No need to add `.catch(err => { console.error(err); process.exit(1) })` * - Supports automatic failure reporting to Slack (!) */ function runScriptWithSlack(fn, opt = {}) { process.on('uncaughtException', err => { console.error('uncaughtException', err); }); process.on('unhandledRejection', err => { console.error('unhandledRejection', err); }); void (async () => { try { const res = await fn(); if (opt.slackOnSuccess) { await onSuccess(res, opt); } setImmediate(() => process.exit(0)); } catch (err) { console.error('runScript failed:', err); onFailure(err, opt); process.exitCode = 1; } })(); } exports.runScriptWithSlack = runScriptWithSlack; async function onSuccess(res, opt) { const { slackOnSuccess: channel } = opt; if (!channel) return; if (!SLACK_WEBHOOK_URL) { return console.warn(colors_1.yellow(`env.SLACK_WEBHOOK_URL is missing, unable to slack on success`)); } let text; if (res) { text = __1.inspectAny(res, { colors: false, }); // Wrap in markdown-text-block if it's anything but plain String if (typeof res !== 'string') { text = '```' + text + '```'; } } else { text = '```empty response```'; } text = `\`${js_lib_1._substringAfterLast(__filename, '/')}\` completed successfully\n\n${text}`; await new __2.SlackSharedService({ webhookUrl: SLACK_WEBHOOK_URL, }) .sendMsg({ text, channel, noLog: true, throwOnError: true, }) .then(() => { console.log(colors_1.dimGrey(`slacked the result to channel: ${channel}`)); }) .catch(_err => { console.log(colors_1.yellow(`failed to slack the result to channel: ${channel}`)); console.error(_err); }); } function onFailure(err, opt) { const channel = process.env.SLACK_ON_FAILURE || opt.slackOnFailure; if (!channel) return; if (!SLACK_WEBHOOK_URL) { return console.warn(colors_1.yellow(`env.SLACK_WEBHOOK_URL is missing, unable to slack on failure`)); } void new __2.SlackSharedService({ webhookUrl: SLACK_WEBHOOK_URL, }) .sendMsg({ text: err, channel, noLog: true, throwOnError: true, }) .then(() => { console.log(colors_1.dimGrey(`slacked the error to channel: ${channel}`)); }) .catch(_err => { console.log(colors_1.yellow(`failed to slack the error to channel: ${channel}`)); console.error(_err); }); } //# sourceMappingURL=runScriptWithSlack.js.map