index.js 1.72 KB
const MODULE_NAME = 'PARTNER-LISTENER.DUMPER';

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

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

const baseDumpDir = path.join('dump', 'partner-listener');
const lastDumpFileName = path.join(baseDumpDir, 'last');

module.exports = async (xid, req, responseBody) => {
    if (
        !config
        || !config.listener
        || !config.listener.partner
        || !config.listener.partner.dump
    ) return;

    const data = `--------
XID: ${xid}
TS: ${moment().format('YYYY-MM-DD HH:mm:ss')}

REQ FROM: ${req.ip}
REQ CONTENT-TYPE: ${req.get('content-type')}
REQ METHOD: ${req.method}
REQ URL: ${req.url}

REQ QUERY-STRING:
${JSON.stringify(req.query, null, 2)}

REQ BODY:
${typeof req.body === 'string' ? req.body : JSON.stringify(req.body, null, 2)}

RES BODY:
${typeof responseBody === 'string' ? responseBody : JSON.stringify(responseBody, null, 2)}
`;

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

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