UNPKG

n-slack

Version:
68 lines (67 loc) 3.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SlackService = void 0; const tslib_1 = require("tslib"); const axios_1 = tslib_1.__importDefault(require("axios")); const assert_1 = tslib_1.__importDefault(require("assert")); const common_1 = require("@nestjs/common"); const constants_1 = require("./constants"); let SlackService = class SlackService { constructor(options, client) { this.options = options; this.client = client; } sendText(text, opts) { return this.postMessage(Object.assign({ text }, opts)); } postMessage(req) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const requestTypes = { api: () => this.runApiRequest(req), webhook: () => this.runWebhookRequest(req), stdout: () => this.runStdoutRequest(req), }; (0, assert_1.default)(requestTypes[this.options.type], "expected option to exist"); yield requestTypes[this.options.type](); }); } runApiRequest(req) { var _a; return tslib_1.__awaiter(this, void 0, void 0, function* () { (0, assert_1.default)(this.options.type === "api"); (0, assert_1.default)(this.client, "expected this.client to be WebClient"); const channel = (_a = req.channel) !== null && _a !== void 0 ? _a : this.options.defaultChannel; (0, assert_1.default)(channel, "neither channel nor defaultChannel was applied"); yield this.client.chat.postMessage(Object.assign(Object.assign({}, req), { channel })); }); } runWebhookRequest(req) { return tslib_1.__awaiter(this, void 0, void 0, function* () { (0, assert_1.default)(this.options.type === "webhook", "expected type to be webhook"); if ("channels" in this.options) { const { channel: userDefinedChannel = this.options.defaultChannel } = req, slackRequest = tslib_1.__rest(req, ["channel"]); (0, assert_1.default)(userDefinedChannel, "neither channel nor defaultChannel was applied"); const channel = this.options.channels.find((c) => c.name === userDefinedChannel); if (!channel) { throw new Error(`The channel ${userDefinedChannel} does not exist. You must add this in the channels option.`); } yield axios_1.default.post(channel.url, slackRequest); return; } (0, assert_1.default)("url" in this.options, "expected url to be defined"); yield axios_1.default.post(this.options.url, req); }); } runStdoutRequest(req) { (0, assert_1.default)(this.options.type === "stdout"); (0, assert_1.default)(this.options.output, "expected output to be defined"); this.options.output(req); } }; SlackService = tslib_1.__decorate([ (0, common_1.Injectable)(), tslib_1.__param(0, (0, common_1.Inject)(constants_1.SLACK_MODULE_OPTIONS)), tslib_1.__param(1, (0, common_1.Inject)(constants_1.SLACK_WEB_CLIENT)), tslib_1.__metadata("design:paramtypes", [Object, Object]) ], SlackService); exports.SlackService = SlackService;