callback.js 2.02 KB
const MODULE_NAME = 'DUMPER.CALLBACK';

const fs = require('fs');

const fsPromise = fs.promises;
const moment = require('moment');
const config = require('komodo-sdk/config');
const logger = require('tektrans-logger');
const path = require('path');
const mkdirIfNotExists = require('../mkdir-if-not-exists');

require('./init');
const vars = require('./vars');

const { baseDumpDir } = vars;
const baseCallbackDumpDir = path.join(baseDumpDir, 'callback');

if (!fs.existsSync(baseCallbackDumpDir)) {
    fs.mkdirSync(baseCallbackDumpDir, { recursive: true });
}

const doNotDump = !config.partner.dump_callback;

module.exports = async (xid, req) => {
    if (!req) return;
    if (doNotDump) return;

    logger.verbose(`${MODULE_NAME} E244F70E: Dumping`, {
        xid,
    });

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

    await mkdirIfNotExists(xid, dumpDir);

    const dumpFileName = path.join(
        dumpDir,
        `callback_${xid}.txt`,
    );

    const data = `-------- BEGIN OF CALLBACK DUMP --------

${moment().format('YYYY-MM-DD HH:mm:ss')}

XID: ${xid}

REMOTE ADDR: ${req.ip}
USER AGENT: ${req.get('user-agent')}
CONTENT-TYPE: ${req.get('content-type')}

HTTP METHOD: ${req.method}
URL: ${req.url}

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

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

-------- END OF CALLBACK DUMP --------
`;

    try {
        logger.verbose(`${MODULE_NAME} ED80B898: Writing file`, {
            xid,
            dumpFileName,
        });

        await fsPromise.writeFile(dumpFileName, data);

        logger.verbose(`${MODULE_NAME} 362AEFC6: Writing last dump file`, { xid });
        await fsPromise.writeFile(
            path.join(baseDumpDir, 'last-callback.txt'),
            data,
        );
    } catch (e) {
        logger.warn(`${MODULE_NAME} 925869BC: Exception on writing dump file`, {
            xid,
            eCode: e.code,
            eMessage: e.message,
        });
    }
};