-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
85 lines (69 loc) · 1.79 KB
/
app.js
File metadata and controls
85 lines (69 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"use strict";
const http = require("http");
const mixin = require("merge-descriptors");
const debug = require("debug")("demo:app");
const Router = require("./router");
const done = require("./util/done").done;
const HTTP_METHODS = require("./util/methods").methods;
exports = module.exports = createApp;
exports.Router = Router;
exports.static = require("./middleware/static.middleware");
let app = {};
app.handle = function(req, res, cb) {
var _done = cb || done;
if (!this._router) {
debug("no routes defined on app");
done(req, res);
return;
}
this._router.handle(req, res, _done);
};
app.use = function(path, fn) {
if (!this._router) {
this._router = new Router();
}
let args = verify(path, fn);
this._router.use(args.path, args.fn);
};
app.listen = function() {
const server = http.createServer(this);
return server.listen.apply(server, arguments);
};
//支持四种http方法
HTTP_METHODS.forEach(function(method) {
app[method] = function(path, fn) {
if (!this._router) {
this._router = new Router();
}
let args = verify(path, fn);
this._router[method](args.path, args.fn);
};
});
//出口函数
function createApp() {
let application = function(req, res) {
application.handle(req, res);
};
mixin(application, app, false);
return application;
}
function verify(path, fn) {
if (typeof path === "function" && typeof fn === "undefined") {
fn = path;
path = "/";
}
if (typeof path !== "string") {
throw new TypeError("Expected path is a string.");
}
if (typeof fn === "undefined") {
throw new Error("Expected a middleware function as second argument.");
} else {
if (typeof fn !== "function") {
throw new TypeError("Expected middleware is a function.");
}
}
return {
path,
fn
};
}