All files / app/middleware http.middleware.js

100% Statements 38/38
100% Branches 16/16
100% Functions 2/2
100% Lines 38/38
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 641x 1x 1x 1x 1x   1x   50x   47x 47x     47x   47x 46x   91x 91x 91x   91x 3x 2x   3x 3x       46x 3x 3x 1x 1x 1x   2x 2x 1x 1x 1x   1x 1x       2x   43x     1x       50x   50x    
const {parse} = require('url');
const pathToRegexp = require('path-to-regexp');
const lodash = require('lodash');
const skip = require('./skip.middleware');
const common = require('./../common');
 
module.exports = function httpMiddleware() {
 
    const http = async function (ctx, next) {
 
        let routers = koahub.configs.router;
        let regexp, regres, index, url, path, query, method = ctx.method;
 
        // 注入params参数
        ctx.params = {};
 
        if (routers && routers.length) {
            for (let router in routers) {
 
                let keys = [];
                regexp = pathToRegexp(routers[router][0], keys, {strict: true, sensitive: true});
                regres = regexp.exec(ctx.path);
 
                if (regres) {
                    for (var key in keys) {
                        ctx.params[keys[key].name] = regres[parseInt(key) + 1];
                    }
                    index = router;
                    break;
                }
            }
 
            if (index) {
                const router = routers[index][1];
                if (lodash.isString(router)) {
                    path = router;
                    query = parse(ctx.url).search || '';
                    url = path + query;
                } else {
                    const routerMethod = router[method.toLowerCase()];
                    if (routerMethod) {
                        path = routerMethod;
                        query = parse(ctx.url).search || '';
                        url = path + query;
                    } else {
                        common.log('Not Found Router');
                        return;
                    }
                }
 
                await common.runHttp(Object.assign(ctx, {originalPath: ctx.path, path: path, url: url}), next);
            } else {
                await common.runHttp(ctx, next);
            }
        } else {
            await common.runHttp(ctx, next);
        }
    };
 
    http.skip = skip;
 
    return http;
}