dumper.js 1.88 KB
const MODULE_NAME = 'CALLBACK.DUMPER';

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 baseDumpDir = 'dump';
const callbackDumpDir = path.join(baseDumpDir, 'callback');

if (!fs.existsSync(baseDumpDir)) {
    logger.verbose(`${MODULE_NAME} D7E3D88E: Creating base dump dir`);
    fs.mkdirSync(baseDumpDir);
}

if (!fs.existsSync(callbackDumpDir)) {
    logger.verbose(`${MODULE_NAME} 002EC4A8: Creating callback dump dir`);
    fs.mkdirSync(callbackDumpDir);
}

module.exports = async (req, res, next) => {
    if (
        !config
        || !config.partner
        || !config.partner.callback
        || !config.partner.callback.dump_request
    ) {
        next();
        return;
    }

    const { xid } = res.locals;

    const data = `--------
XID: ${xid}
PID: ${process.pid}
DATE: ${moment().format('YYYY-MM-DD HH:mm:ss.SSS')}
REMOTE-ADDR: ${req.ip}
USER-AGENT: ${req.get('user-agent')}
METHOD: ${req.method}
URL: ${req.url}

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

REQ-CONTENT-TYPE: ${req.get('content-type')}
REQ-BODY-TYPEOF: ${typeof req.body}
REQ-BODY: 
${(req.body && typeof req.body === 'object' && JSON.stringify(req.body, null, 2)) || req.body}
`;

    const dumpDir = path.join(
        callbackDumpDir,
        moment().format('YYYY-MM-DD'),
    );

    try {
        await fsPromise.stat(dumpDir);
    } catch (e) {
        await fsPromise.mkdir(dumpDir, { recursive: true });
    }

    await fsPromise.writeFile(
        path.join(
            dumpDir,
            [
                moment().format('YYMMDD_HHmmss_SSS'),
                xid,
            ].join('_'),
        ),
        data,
    );

    await fsPromise.writeFile(
        path.join(callbackDumpDir, 'last'),
        data,
    );

    next();
};