const HttpRequest = function() {
this.query = ''
}
function HttpResponse() {
this.body = []
this.status = 0;
}
HttpResponse.prototype.write = function(block) {
this.body.push(block)
}
HttpResponse.prototype.display = function() {
console.log(this.body, this.status)
}
const HttpApplication = function() {
this.caches = []
}
HttpApplication.prototype.use = function(middleware) {
this.caches.push(middleware)
}
HttpApplication.prototype._createPipeLineItem = (fn, next) => {
return (req, rsp) => {
fn.call(this, req, rsp, next)
}
}
HttpApplication.prototype.applyRequest = function(req, rsp) {
const middleware = this.caches.map(item => item).reverse()
let lastHandler = (req, rsp) => {
rsp.write('404')
rsp.status = 404
}
for (let index = 0; index < middleware.length; index++) {
const element = middleware[index];
lastHandler = this._createPipeLineItem(element, lastHandler)
}
lastHandler(req, rsp)
}
const app = new HttpApplication()
app.use((req, rsp, next) => {
rsp.write('first middleware')
next(req, rsp)
rsp.write('first middleware end')
})
app.use((req, rsp, next) => {
rsp.write('second middleware')
rsp.status = 200
// next(req, rsp)
})
const req = new HttpRequest()
const rsp = new HttpResponse()
app.applyRequest(req, rsp)
rsp.display()