- The process of creating an application should be separated from the application itself.
- The process of routing and creating applications is also separated.
The following implements the separation of the process of creating an application from the application itself:
express.js
const Application = require("./application");
function createApplication() {
// 通过类来实现分离操作
return new Application();
}
module.exports = createApplication;
Every time you create an application, the routing system should be irrelevant and a completely new routing system should be created.
Newapplication.js
const http = require("http");
const url = require("url");
function Application() {
this.routers = [
{
path: "*",
method: "all",
handler: (req, res) => {
res.end(`kaimo-express Cannot ${
req.method} ${
req.url}`);
}
} // 默认路由
];
}
Application.prototype.get = function (path, handler) {
this.routers.push({
path,
method: "get",
handler
});
};
Application.prototype.listen = function () {
const server = http.createServer((req, res) => {
const {
pathname } = url.parse(req.url);
const requestMethod = req.method.toLowerCase();
for (let i = 1; i < this.routers.length; i++) {
let {
path, method, handler } = this.routers[i];
if (path === pathname && method === requestMethod) {
return handler(req, res);
}
}
return this.routers[0].handler(req, res);
});
server.listen(...arguments);
};
module.exports = Application;
have a test:
const express = require("./kaimo-express");
const app = express();
// 调用回调时 会将原生的 req 和 res 传入(req,res 在内部也被扩展了)
// 内部不会将回调函数包装成 promise
app.get("/", (req, res) => {
res.end("ok");
});
app.get("/add", (req, res) => {
res.end("add");
});
app.listen(3000, () => {
console.log(`server start 3000`);
console.log(`在线访问地址:http://localhost:3000/`);
});