Router

Router

new Router(io, opt) → {Router}

constructor - create new router

Parameters:
Name Type Description
io SocketIO
opt Object

{delimiter: ':'}

Source:
Returns:
Type
Router

Methods

(private) onerror(err)

onerror - error handler

Parameters:
Name Type Description
err Error
Source:

route(path, middlewares) → {undefined}

route - add new route

Parameters:
Name Type Description
path String
middlewares function | Array.<function()>

function may return promise

Source:
Returns:
Type
undefined
Examples
// success response
let router = new Router(io);
router.route('ping', (ctx, next) => {
    ctx.success('pong');
    return next();
});
// error response
let router = new Router(io);
router.route('err-ping', (ctx, next) => {
    ctx.success('because f*ck you!');
    return next();
});
// error response (throw)
let router = new Router(io);
router.route('err-ping', (ctx, next) => {
    throw {err: 'wtf', code: 400, description: 'WTF!?'};
    // error always prevent next()
});
// compose middlewares
let router = new Router(io);
router.route('compose', [
    (ctx, next) => {
        ctx.result = 1;
        return next();
    },
    (ctx, next) => {
        ctx.result++;
        return next();
    },
    (ctx, next) => {
        ctx.success(ctx.result);  // return 2
    }
]);
// async handler
let co = require('co');
let router = new Router(io);
router.route('async', co.wrap(function*(ctx, next) {
    let data = yield loadFromDataBase();
    ctx.success(data);
}));

use(middlewares) → {undefined}

use - global middleware

Parameters:
Name Type Description
middlewares function | Array.<function()>

function may return promise

Source:
Returns:
Type
undefined
Example
let router = new Router(io);
router.use((ctx, next) => {
    console.info(`request ${ctx.event.name}`, ctx.data);
    next().then(() => {
        console.info(
            `request ${ctx.event.name} end with ${ctx.status}`,
            ctx.result
        );
    });
});
router.route('ping', (ctx) => {ctx.success('pong')});