UNPKG

@cto.ai/ops-rc

Version:

💻 CTO.ai Ops - The CLI built for Teams 🚀

149 lines (148 loc) 6.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const fs = tslib_1.__importStar(require("fs-extra")); const path = tslib_1.__importStar(require("path")); const assert_1 = tslib_1.__importDefault(require("assert")); const axios_1 = tslib_1.__importDefault(require("axios")); const utils_1 = require("./../../utils"); const base_1 = tslib_1.__importStar(require("../../base")); const CustomErrors_1 = require("./../../errors/CustomErrors"); const opConfig_1 = require("../../constants/opConfig"); const env_1 = require("../../constants/env"); class SubscribeEvent extends base_1.default { constructor() { super(...arguments); this.opResults = []; this.startSpinner = async (inputs) => { this.ux.spinner.start(`🔍 ${this.ux.colors.white('Validating your teams and ops')}`); return inputs; }; this.stopSpinner = async (inputs) => { this.ux.spinner.stop(`${this.ux.colors.successGreen('Done')}`); return inputs; }; this.getActiveTeam = async (inputs) => { try { return Object.assign(Object.assign({}, inputs), { activeTeam: inputs.config.team, teams: [] }); } catch (err) { this.debug('%O', err); throw new CustomErrors_1.ConfigError(err); } }; this.getTeamsFromApi = async (inputs) => { try { const { data: teams } = await this.services.api.find('/private/teams', { headers: { Authorization: inputs.config.tokens.accessToken }, }); return Object.assign(Object.assign({}, inputs), { teams, activeTeam: {} }); } catch (err) { this.debug('%O', err); throw new CustomErrors_1.APIError(err); } }; this.getApiOps = async (inputs) => { try { const { data: opResults } = await this.services.api.find(`/private/teams/${inputs.config.team.name}/ops`, { headers: { Authorization: this.accessToken, }, }); this.opResults = opResults; return Object.assign(Object.assign({}, inputs), { opResults }); } catch (err) { this.debug('%0', err); throw new CustomErrors_1.APIError(err); } }; this.getLocalOps = async (inputs) => { try { const manifest = await fs.readFile(path.join(process.cwd(), opConfig_1.OP_FILE), 'utf8'); if (!manifest) return inputs; const { ops = [] } = utils_1.parseYaml(manifest); const localCommands = ops.map(ops => (Object.assign(Object.assign({}, ops), { local: true }))); return Object.assign(Object.assign({}, inputs), { opResults: [...inputs.opResults, ...localCommands] }); } catch (_a) { return Object.assign({}, inputs); } }; this.sendAnalytics = (inputs) => { const { config, teams = [] } = inputs; this.services.analytics.track('Ops CLI Subscribe:Event', { username: config.user.username, results: teams.length, }, config); }; this.sendSubscriptionRequest = async ({ userId, teamId, teamName, opName, eventName, source, config }) => { const data = { user_id: userId, team_id: teamId, team_name: teamName, op_name: opName, event_name: eventName, source }; const options = { headers: { 'Authorization': `Bearer ${config.tokens.accessToken}` } }; return axios_1.default.post(`${env_1.EVENTS_SERVICE}/v1/events/subscribe`, data, options); }; this.showRunMessage = ({ msg, name, team, op }) => { this.log(this.ux.colors.white(`Your team ${team.name}, has succesfully being subscribed to event ${name}, with op ${op.name}`)); }; } async run() { const { flags } = this.parse(SubscribeEvent); const config = await this.isLoggedIn(); assert_1.default.ok(env_1.EVENTS_SERVICE, 'Need to set EVENTS_SERVICE url as a environment variable'); try { const listPipeline = utils_1.asyncPipe(this.startSpinner, this.getActiveTeam, this.getTeamsFromApi, this.getApiOps, this.getLocalOps, this.stopSpinner); const { opResults, teams } = await listPipeline({ config }); const op = opResults.find((op) => flags.op === op.name); const team = teams.find((t) => flags.team === t.name); if (!team) { throw new Error('Valid team name required'); } if (!op) { throw new Error('Valid op name required'); } const [source, ...eventName] = flags.name.split('.'); // rejoin eventName const joinedEvent = eventName.join('.'); const result = await this.sendSubscriptionRequest({ userId: config.user.id, teamId: team.id, teamName: team.name, opName: op.name, eventName: joinedEvent, source, config }); this.showRunMessage({ msg: result.data.msg, team, op, name: flags.name }); } catch (err) { this.ux.spinner.stop(this.ux.colors.red(`${this.ux.colors.errorRed('Failed')}`)); this.debug('%O', err); this.config.runHook('error', { err: err.response ? new Error(err.response.data.message) : err, accessToken: config.tokens.accessToken, }); } } } exports.default = SubscribeEvent; // opResults: (ListInputs)[] = [] SubscribeEvent.description = 'Subscribe to an event'; SubscribeEvent.flags = { help: base_1.flags.help({ char: 'h' }), team: base_1.flags.string({ char: 't', description: 'team to subscribe to an event', required: true }), name: base_1.flags.string({ char: 'n', description: 'name of the event to subscribe', required: true }), op: base_1.flags.string({ char: 'o', description: 'operation to trigger on the ocurrance of the event specified by -n', required: true }), };