nodejs框架express路由的大致原理

2019-03-06 09:56:16 浏览数 (1)

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

代码语言:javascript复制
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()

0 人点赞