all files / lib/ router.js

100% Statements 29/29
100% Branches 4/4
100% Functions 2/2
100% Lines 29/29
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    1× 1× 1×   1× 1×   1×     10×     10×     10× 10× 10×     10× 1× 9×           9×     10× 9× 9× 1×           8×   8× 8×   8×   7×         10×     1× 7× 7× 7×        
'use strict';
 
const PATH = require('path');
const Routes = require('./routes');
const Conf = require('./support/configuration');
 
const Memory = new WeakMap();
const Name = 'plugins:router';
 
module.exports = function router() {
 
    // Inject router's configuration (and generate paths)
    this.conf = Conf;
 
    // return an instance of an object
    const router$ = this.observable.of(new (class Router extends Object{}));
 
    // Make sure the router file exists
    const filename$ = router$.switchMap(router => {
        const filename = this.path.router;
        return this.util.rx.path(filename)
            .isFile()
            .do(isFile => {
                if (!isFile)
                    throw this.error.type({ name:'router', type:'File', data:filename });
                Object.defineProperty(router, 'filename', {
                    enumerable : true,
                    value      : filename
                });
            })
            .mapTo(router)
            .do(router => this.debug(Name, 'filename', router))
    });
 
    const routes$ = filename$.switchMap(router => {
        let routes = require(router.filename);
        if (!this.util.is(routes).object())
            throw this.error.type({
                name: 'router.routes',
                type: 'Object',
                data: router.routes
            });
        // Avoid modifying the original routing reference by copying the object.
        routes = this.util.object({}).merge(routes);
        // define the getter and set the default value
        Object.defineProperty(router, 'routes', { get: getter.bind(this) });
        Memory.set(this, new Routes(this))
        // Resolve each route observable and return it.
        return this.observable
            .from(Object.keys(routes))
            .concatMap(path => router.routes.load(path, routes[path]))
            .toArray()
            .mapTo(router);
    });
 
    return routes$.mapTo(this);
}
 
function getter() {
    const routes = Memory.get(this);
    this.debug(Name, 'getter', routes);
    return routes;
}