@mondaycom/apps-cli
Version:
A cli tool to manage apps (and monday-code projects) in monday.com
82 lines (81 loc) • 3.44 kB
JavaScript
import Pusher from 'pusher-js';
import { isDefined } from '../utils/validations.js';
import { LogItemSeverity } from '../types/communication/log-item-types.js';
import { StreamLogType } from '../types/services/client-channel-service.js';
import logger from '../utils/logger.js';
const mapSeverityToLogFunction = {
[LogItemSeverity.DEBUG]: (...args) => logger.debug(args),
[LogItemSeverity.INFO]: logger.info,
[LogItemSeverity.WARNING]: logger.warn,
[LogItemSeverity.ERROR]: logger.error,
};
const SUPPORTED_LOG_SEVERITIES = Object.keys(mapSeverityToLogFunction);
export const streamMessages = (clientChannel) => {
const DEBUG_TAG = 'streamMessages';
return new Promise(resolve => {
try {
if (!clientChannel) {
throw new Error('ClientChannel is missing.');
}
if (!clientChannel.credentials) {
throw new Error('ClientChannel credentials are missing.');
}
const writePusherLogs = (data) => {
data.map(logItem => {
const object = { request: logItem.request, response: logItem.response };
let logMethod = logger.log;
const severity = logItem.severity;
const isSeverityValid = SUPPORTED_LOG_SEVERITIES.includes(severity);
if (isSeverityValid && isDefined(severity)) {
logMethod = mapSeverityToLogFunction[severity];
}
return logItem.message
? logMethod(`[${logItem.type}]${logItem.message}`)
: logMethod(object, `[${logItem.type}]`);
});
};
const disconnect = (channel) => {
if (channel) {
channel.unsubscribe();
channel.unbind_all();
}
logger.log(`------------------
Closed connection.`);
resolve();
};
Pusher.logToConsole = true;
Pusher.log = msg => {
logger.debug(msg, DEBUG_TAG);
};
const pusher = new Pusher(clientChannel.credentials.key, {
cluster: clientChannel.cluster,
});
const channel = pusher.subscribe(clientChannel.channelName);
channel.bind(clientChannel.channelEvents[0], function (data) {
switch (data?.type) {
case StreamLogType.HTTP:
case StreamLogType.CONSOLE: {
writePusherLogs(data.data);
break;
}
case StreamLogType.DISCONNECT: {
disconnect(channel);
break;
}
}
});
logger.debug(`Trying to listen to channel: ${clientChannel.channelName}`, DEBUG_TAG);
pusher.connection.bind('connected', () => {
logger.log(`Fetching logs:
------------------`);
setTimeout(() => {
disconnect(channel);
}, clientChannel.ttl * 1000);
});
}
catch (error) {
logger.debug(error, DEBUG_TAG);
throw new Error(`Failed to stream messages to channel "${clientChannel.channelName}"`);
}
});
};