req.js 1.64 KB
const MODULE_NAME = 'CORE-CALLBACK.DUMPER.REQ';

// const fs = require('fs');
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 mkdirIfNotExists = require('../../utils/mkdir-if-not-exists');
const mkdirp = require('mkdirp');

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

module.exports = async (req, res, next) => {
    if (
        !config
        || !config.listener
        || !config.listener.core
        || !config.listener.core.dump
    ) {
        next();
        return;
    }

    const { xid } = res.locals;

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

REQ-CONTENT-TYPE: ${req.get('content-type')}

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

REQ BODY:
${JSON.stringify(req.body, null, 2)}
`;


    const dumpFileName = path.join(
        baseDumpDir,
        moment().format('YYYY-MM-DD'),
        [
            'req',
            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} E77C2B23: Exception on dumping file`, {
            xid,
            eCode: e.code,
            eMessage: e.eMessage,
        });
    }

    next();
};