node框架express路由的大致原理

昨晚准备洗澡的时候,突然想实现一下express的路由逻辑,但时间有限,只能先写这么多。这个不完全是express的路由原理,只是提供一点思路,具体逻辑可以参考源码,express的路由,好不好不敢说,但是做法挺新颖的,给我一个新的思想。

function Layer(config) {
    if (config.handle instanceof route) {
        this.route = config.handle;
    } else {
        this.handle = config.handle;
    }
}

Layer.prototype = {

}

function route() {
    this.stack = [];
}

route.prototype = {
    dispatch: function(done) {
        if (this.stack.length === 0) {
            return;
        } else {
            this.next(done);
        }
    },
    next: function(done) {
        var layer = this.stack.shift();
        if (!layer) {
            done();
            return;
        }
        layer.handle(this.next.bind(this,done));    
    },
    add: function(fn) {
        this.stack.push(new Layer({handle: fn}));
        return this;
    }
}

function router() {
    this.stack = [];
}

router.prototype = {
    dispatch: function(done) {
        if (this.stack.length === 0) {
            return 
        } else {
            this.next(done);
        }
    },
    next: function(done) {
        var layer = this.stack.shift();
        if (!layer) {
            done();
            return
        }

        if (layer.route) {
            layer.route.dispatch(this.next.bind(this,done));
        }  else {
            layer.handle(this.next.bind(this,done));
        }   
    },
    add: function(fn) {
        this.stack.push(new Layer({handle: fn}));
    },
    route: function(fn) {
        this.stack.push(new Layer({handle: new route().add(fn)}))
    }
}

function app() {
    this.router = new router();
}

app.prototype = {
    initRouter: function() {
        if (this.router) {
            //懒初始化,有时候也不是很好
        }
    },
    use: function(fn) {
        this.router.add(fn);
    },
    route: function(fn) {
        this.router.route(fn);
    },
    start: function() {
        this.router.dispatch(function(){
            console.log('done');
        });
    }
}

var myapp = new app();
myapp.use(function(next) {
    console.log('start');
    next()
});

myapp.use(function(next) {
    console.log('middle');
    next()
});

myapp.route(function(next) {
    console.log('app');
    next()
});
myapp.start()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值