index.js 1.77 KB
const compose = require('koa-compose');
const _ = require('lodash');

const enable = require('./enable');
const qpsPath = require('./qps-path');

const disableBelow = require('./disable');
const ipFilter = require('./ip');
const userFilter = require('./user');
const userAgentFilter = require('./useragent');
const xhrFilter = require('./xhr');
const whitelistIpFilter = require('./whitelist-ip');
const whitelistPathFilter = require('./whitelist-path');
const qps = require('./qps');

const logger = global.yoho.logger;

const APP_NAME = {
    'yohobuy-node': 'pc',
    'yohobuywap-node': 'wap',
    UNKNOWN: ''
};

const APP_TYPE = {
    'yohobuy-node': 'web',
    'yohobuywap-node': 'h5',
    UNKNOWN: ''
};

module.exports = () => {
    const handlers = compose([
        enable,
        qpsPath,

        disableBelow,
        userFilter,
        xhrFilter,
        whitelistIpFilter,
        whitelistPathFilter,
        ipFilter,
        userAgentFilter,
        qps
    ]);

    return async(m) => {
        logger.debug('[request] %j', m);

        const user = {
            uid: _.parseInt(_.get(m, 'fields.uid', '0').replace(/\"/g, ''), 10),
            ip: _.get(m, 'fields.ip', '').replace(/\"/g, ''),
            app: APP_NAME[_.get(m, 'tags.app', 'UNKNOWN')],
            appName: _.get(m, 'tags.app', ''),
            appType: APP_TYPE[_.get(m, 'tags.app', 'UNKNOWN')],
            path: decodeURIComponent(_.get(m, 'fields.path', '').replace(/\"/g, '')),
            userAgent: decodeURIComponent(_.get(m, 'fields.userAgent', '').replace(/\"/g, '')),
            ajax: _.parseInt(_.get(m, 'fields.ajax', 0))
        };

        if (!user.ip || !user.app) {
            logger.debug('miss ip or app %j but get %j', m, user);
            return;
        }

        await handlers({user});
    };
};