sender.js 1.92 KB
const MODULE_NAME = 'CORE-CALLBACK.DUMPER.SENDER';

const fsPromise = require('fs').promises;
const path = require('path');
const config = require('komodo-sdk/config');
const logger = require('tektrans-logger');
const moment = require('moment');
const mkdirp = require('mkdirp');

// const mkdirIfNotExists = require('../../utils/mkdir-if-not-exists');

const baseDumpDir = path.join('dump', 'core-callback');
const lastDumpFileName = path.join(baseDumpDir, 'last-sent');

module.exports = async (xid, httpMethod, endpointUrl, params, axiosResponse, axiosError) => {
    if (
        !config
        || !config.listener
        || !config.listener.core
        || !config.listener.core.dump
    ) {
        return;
    }

    const data = `--------
XID: ${xid}
PID: ${process.pid}
DATE: ${moment().format('YYYY-MM-DD HH:mm:ss.SSS')}

HTTP METHOD: ${httpMethod}
ENDPOINT URL: ${endpointUrl}

REQ PARAMS:
${JSON.stringify(params, null, 2)}

ERROR CODE: ${(axiosError && axiosError.code) || ''}
ERROR MESSAGE: ${(axiosError && axiosError.message) || ''}

RES HTTP STATUS: ${axiosResponse && axiosResponse.status}
RES BODY:
${
    axiosResponse && axiosResponse.data && (
        ((typeof axiosResponse.data === 'string') && axiosResponse.data)
        || JSON.stringify(axiosResponse.data, null, 2)
    )
}
`;

    const dumpFileName = path.join(
        baseDumpDir,
        moment().format('YYYY-MM-DD'),
        [
            'sent',
            moment().format('YYMMDD_HHmmss_SSS'),
            xid,
        ].join('_'),
    );

    try {
        // await mkdirIfNotExists(xid, path.dirname(dumpFileName));
        await mkdirp(path.dirname(dumpFileName));
        await fsPromise.writeFile(lastDumpFileName, data);
        await fsPromise.writeFile(dumpFileName, data);
    } catch (e) {
        logger.warn(`${MODULE_NAME} 9BA99454: Exception on dumping file`, {
            xid,
            eCode: e.code,
            eMessage: e.eMessage,
        });
    }
};