index.js 2.39 KB
const MODULE_NAME = 'HTTP-SERVER.ROUTER.PRODUCTS';

const express = require('express');
const logger = require('tektrans-logger');

const configData = require('../../../config/data');
const configSaveProduct = require('../../../config/save-product');
const configRemoveProduct = require('../../../config/remove-product');

const router = express.Router();

module.exports = router;

const pageIndex = async (req, res) => {
    const { xid } = res.locals;
    try {
        logger.verbose(`${MODULE_NAME} F1BF0675: get product configuration`, { xid });
        const products = (await configData.all()).products || {};
        res.json({ error: false, message: 'OK', result: products });
    } catch (e) {
        logger.warn(`${MODULE_NAME} 839E55E0: Exception.`, {
            xid, eMessage: e.message, eCode: e.code,
        });
        res.status(500).json({
            error: true,
            error_code: e.code,
            message: e.message,
        });
    }
};

const pageSave = async (req, res) => {
    const { xid } = res.locals;
    const { name, remote = null, active = 0 } = req.body;
    try {
        logger.verbose(`${MODULE_NAME} 59CB2503: save product configuration`, { xid, data: req.body });

        const params = {
            name,
            remote,
            active,
        };
        await configSaveProduct(xid, name, params);
        res.json({ error: false, message: 'OK' });
    } catch (e) {
        logger.warn(`${MODULE_NAME} 47F57E23: Exception.`, {
            xid, eMessage: e.message, eCode: e.code,
        });
        res.status(500).json({
            error: true,
            error_code: e.code,
            message: e.message,
        });
    }
};

const pageRemove = async (req, res) => {
    const { xid } = res.locals;
    const { name } = req.body;
    try {
        logger.verbose(`${MODULE_NAME} E94A7B38: remove product configuration`, { xid, name });

        await configRemoveProduct(xid, name);
        res.json({ error: false, message: 'OK' });
    } catch (e) {
        logger.warn(`${MODULE_NAME} 955FD7E3: Exception.`, {
            xid, eMessage: e.message, eCode: e.code,
        });
        res.status(500).json({
            error: true,
            error_code: e.code,
            message: e.message,
        });
    }
};

router.get('/', [express.json()], pageIndex);

router.post('/save', [express.json()], pageSave);
router.post('/remove', [express.json()], pageRemove);