All files / lib Lark.js

97.56% Statements 40/41
90.91% Branches 10/11
100% Functions 7/7
97.56% Lines 40/41
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          1x 1x 1x   1x 1x 1x 1x 1x   1x       3x 6x 1x     8x 8x 8x     6x   8x   8x   8x 8x   8x 8x 8x       9x   9x 7x 7x 35x     35x 35x   35x 35x 15x         9x 8x 8x 8x 8x   8x         1x  
/**
 * Defination of class Lark
 **/
'use strict';
 
const assert          = require('assert');
const misc            = require('vi-misc');
const path            = require('path');
 
const Koa             = require('koa');
const LarkConfig      = require('lark-config');
const LarkMVC         = require('lark-mvc');
const LarkRouter      = require('lark-router');
const LarkRoutes      = require('lark-router-config');
 
global.$ = global.$ || {};
 
class Lark extends Koa {
 
    static get Model() { return LarkMVC.Model; }
    static get Controller() { return LarkMVC.Controller; }
    static get View() { return LarkMVC.View; }
 
    constructor(...args) {
        super(...args);
        try {
            this.pkg = require(path.join(misc.path.root, 'package.json'));
        }
        catch (e) {
            this.pkg = {};
        }
        this.pkg = this.pkg['lark'] || {};
 
        this._servers = [];
 
        this.config = new LarkConfig(path.join(__dirname, '../configs'));
        this.config.use(this.pkg['configs']);
 
        this.router = new LarkRouter();
        this.routes = new LarkRoutes();
        this.mvc    = new LarkMVC();
    }
 
    start(options = {}) {
        this.config.use(options);
 
        if (this.config.has('bootstrap/middlewares')) {
            const middlewares = this.config.get('bootstrap/middlewares');
            for (let middlewareName of middlewares) {
                Iif (middlewareName.startsWith('.')) {
                    middlewareName = misc.path.absolute(middlewareName);
                }
                let middlewareGenerator = require(middlewareName);
                assert(middlewareGenerator instanceof Function,
                    `middleware generator ${middlewareName} should be a Function `);
                const middleware = middlewareGenerator(this);
                if (middleware instanceof Function) {
                    this.use(middleware);
                }
            }
        }
 
        assert(this.config.has('server/port'), 'No server port found in config["server/port"]');
        return new Promise(resolve => {
            const port = this.config.get('server/port');
            let server = this.listen(port, () => {
                resolve({port, server});
            });
            this._servers.push(server);
        });
    }
}
 
module.exports = Lark;