All files / app common.js

100% Statements 111/111
100% Branches 72/72
100% Functions 4/4
100% Lines 110/110
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 2871x 1x 1x   1x                 99x 99x 98x     99x 99x 99x   99x     1x     4x 4x     5x 5x 5x     89x 89x   89x 82x 82x     7x 7x 2x 2x 2x     5x 5x       99x                       44x 44x 44x   42x 42x     42x 1x     41x     39x 80x 1x         39x 35x     39x 1x       38x 3x     38x 1x       37x 2x     37x 1x     36x     36x 32x       4x 2x     4x 1x       3x 2x     3x 2x     1x       2x 1x   1x 1x         2x 1x   1x 1x                           47x 47x 3x 3x       44x 2609x 1x         43x 43x 1x 1x     42x                   1202x                     8x 8x 2x 2x   6x 6x 5x 4x                           80x 1x   79x                   1471x 1471x 50x   1421x                     21x 19x   2x 2x 2x 2x 2x                     1206x 49x      
const co = require('co');
const lodash = require('lodash');
const moment = require('moment');
 
module.exports = {
 
    /**
     * get module, controller, action from path
     * @param path
     * @returns {{module, controller, action}}
     */
    getModuleControllerAction(path) {
 
        let paths = [];
        if (path != '/') {
            paths = path.substr(1, path.length).split('/');
        }
 
        let module = koahub.config('default_module');
        let controller = koahub.config('default_controller');
        let action = koahub.config('default_action');
 
        switch (paths.length) {
            case 0:
 
                break;
            case 1:
 
                module = paths[0];
                break;
            case 2:
 
                module = paths[0];
                controller = paths[1];
                break;
            default:
 
                module = paths.shift();
                action = paths.pop();
 
                if (koahub.controllers[`/${module}/${paths.join('/')}`]) {
                    controller = paths.join('/');
                    break;
                }
 
                paths.push(action);
                if (koahub.controllers[`/${module}/${paths.join('/')}`]) {
                    controller = paths.join('/');
                    action = koahub.config('default_action');
                    break;
                }
 
                action = paths.pop();
                controller = paths.join('/');
 
        }
 
        return {module, controller, action};
    },
 
    /**
     * run controller && action controller
     * @param ctx
     * @param next
     * @param args
     * @returns {Promise.<*>}
     */
    async runController(ctx, next, ...args){
 
        const {module, controller, action} = this.getModuleControllerAction(ctx.path);
        const ctrl = koahub.controllers[`/${module}/${controller}`];
        if (ctrl) {
 
            const _ctrl = new ctrl(ctx, next);
            const methods = Object.getOwnPropertyNames(ctrl.prototype);
 
            // constructor不响应404,中断执行
            if (ctx.status != 404) {
                return;
            }
 
            if (lodash.includes(methods, action)) {
 
                let result;
                let parseResult = function (data) {
                    if (data) {
                        result = data;
                    }
                };
 
                // 控制器初始化
                if (lodash.includes(methods, '_initialize')) {
                    parseResult(await this.getPromiseFunction(_ctrl, '_initialize')(...args));
                }
                // 控制器初始化不响应404,中断执行
                if (ctx.status != 404) {
                    return;
                }
 
                // 控制器前置
                if (lodash.includes(methods, '_before')) {
                    parseResult(await this.getPromiseFunction(_ctrl, '_before')(...args));
                }
                // 控制器前置不响应404,中断执行
                if (ctx.status != 404) {
                    return;
                }
 
                // 方法前置
                if (lodash.includes(methods, `_before_${action}`)) {
                    parseResult(await this.getPromiseFunction(_ctrl, `_before_${action}`)(...args));
                }
                // 方法前置不响应404,中断执行
                if (ctx.status != 404) {
                    return;
                }
 
                parseResult(await this.getPromiseFunction(_ctrl, action)(...args));
 
                // 不响应404,中断执行
                if (ctx.status != 404) {
                    return;
                }
 
                // 方法后置
                if (lodash.includes(methods, `_after_${action}`)) {
                    parseResult(await this.getPromiseFunction(_ctrl, `_after_${action}`)(...args));
                }
                // 方法后置不响应404,中断执行
                if (ctx.status != 404) {
                    return;
                }
 
                // 控制器后置
                if (lodash.includes(methods, '_after')) {
                    parseResult(await this.getPromiseFunction(_ctrl, '_after')(...args));
                }
                // 控制器后置不响应404,中断执行
                if (ctx.status != 404) {
                    return;
                }
 
                return result;
            } else {
 
                // 控制器空操作
                if (lodash.includes(methods, '_empty')) {
                    return this.runController(Object.assign(ctx, {path: `/${module}/${controller}/_empty`}), next, ...args);
                } else {
                    this.log('Not Found Action');
                    return;
                }
            }
        } else {
 
            if (koahub.controllers[`/${module}/empty`]) {
                return this.runController(Object.assign(ctx, {path: `/${module}/empty/${action}`}), next, ...args);
            } else {
                this.log('Not Found Controller');
                return;
            }
        }
    },
 
    /**
     * run http filter ctx && controller methods
     * @param ctx
     * @param next
     * @param args
     * @returns {Promise.<*|Promise.<*>>}
     */
    async runHttp(ctx, next, ...args) {
 
        const {module, controller, action} = this.getModuleControllerAction(ctx.path);
        if (!lodash.includes(koahub.modules, module)) {
            this.log('Not Found Module');
            return;
        }
 
        // 移除控制器中跟ctx中同名的属性
        for (let name in ctx) {
            if (typeof ctx[name] !== 'function' && action === name) {
                throw new Error(`Don\'t use the "${action}" action in the controller`);
            }
        }
 
        // 过滤控制器默认方法
        const filters = ['constructor', '_initialize', '_before', `_before_${action}`, `_after_${action}`, '_after', '_empty'];
        if (lodash.includes(filters, action)) {
            this.log('Don\'t access the "${action}"');
            return;
        }
 
        return await this.runController(ctx, next, ...args);
    },
 
    /**
     * Check whether a function is generator.
     *
     * @param  {Function} fn
     * @return {Boolean}
     */
    isGeneratorFunction(fn) {
        return typeof fn === 'function' &&
            fn.constructor &&
            fn.constructor.name === 'GeneratorFunction'
    },
 
    /**
     * Parase express middleware to koa middleware
     * @param fn
     * @returns {Function}
     */
    expressMiddlewareToKoaMiddleware(fn) {
        return function (ctx, next) {
            if (fn.length < 3) {
                fn(ctx.req, ctx.res);
                return next();
            } else {
                return new Promise((resolve, reject) => {
                    fn(ctx.req, ctx.res, err => {
                        if (err) reject(err)
                        else resolve(next())
                    })
                })
            }
        }
    },
 
    /**
     * generator to promise
     * @param instance
     * @param method
     * @returns {Function}
     */
    getPromiseFunction(instance, method) {
        if (this.isGeneratorFunction(instance[method])) {
            return co.wrap(instance[method]).bind(instance);
        }
        return instance[method].bind(instance);
    },
 
    /**
     * return es6 module or common module
     * @param file
     * @returns {*}
     */
    requireDefault(file){
 
        const lib = require(file);
        if (lib.hasOwnProperty('default') && Object.keys(lib).length === 1) {
            return lib.default;
        } else {
            return lib;
        }
    },
 
    /**
     * console format
     * @param log
     * @param type
     */
    log(log, type = 'log') {
 
        if (typeof log === 'string') {
            console[type](`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [Koahub] ${log}`);
        } else {
            const msg = log.stack || log.toString();
            console[type]();
            console[type](`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [Koahub] [Log]`);
            console[type](msg);
            console[type]();
        }
    },
 
    /**
     * array customizer
     * @param objValue
     * @param srcValue
     * @returns {string|*|Array.<T>}
     */
    arrayCustomizer(objValue, srcValue) {
        if (lodash.isArray(objValue)) {
            return objValue.concat(srcValue);
        }
    }
}