get-prepaid.js 1.92 KB
const MODULE_NAME = 'PULL.GET-PREPAID';

const logger = require('tektrans-logger');
const axios = require('axios').default;
const uniqid = require('uniqid');
const config = require('../config');
const configData = require('../config/data');
const actions = require('../actions');

const client = axios.create({
    baseURL: config.core.url,
    timeout: config.core.request_timeout_ms,
    headers: {
        'x-access-token': config.core.access_token,
    },
});

let onPull = false;

/**
 * pull unprocessed prepaid transaction from core
 */
module.exports = async () => {
    logger.verbose(`${MODULE_NAME} 385A1B0D: Pull prepaid transaction from core`);
    if (onPull) {
        logger.verbose(`${MODULE_NAME} 6563C2C9: Pull prepaid already running`);
        return false;
    }
    onPull = true;

    const xid = uniqid();

    try {
        const products = await configData.getActiveProductArray(xid);
        const response = await client.post('/transactions/prepaid-pull', {
            gateway: {
                name: config.name,
                url: `${config.url}:${config.port}/apikey/${config.apikey}`,
            },
            products,
        });
        if (response.data.error) {
            logger.info(`${MODULE_NAME} A397BA74: Error when pulling prepaid transaction`, {
                xid,
                message: response.data.message,
                error: response.data.error,
            });
        }

        if (!response.data.result) {
            logger.info(`${MODULE_NAME} 712130A5: Empty prepaid transaction result`, {
                xid,
                result: response.data.result,
            });
            return null;
        }

        await actions.buy(xid, response.data.result);
    } catch (e) {
        logger.warn(`${MODULE_NAME} 008B2FA5: Exception`, {
            xid,
            message: e.message,
            code: e.code,
        });
    } finally {
        onPull = false;
    }
    return true;
};