-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
92 lines (78 loc) · 2.44 KB
/
server.js
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
86
87
88
89
90
91
92
var http = require('http');
var Pretender = require('./pretender');
var path = require('path');
function PretenderRequest(method, url) {
this.method = method;
this.url = url;
}
PretenderRequest.prototype = {
method: null,
url: null,
respond: function(status, headers, body) {},
_progress: function() {},
upload: {_progress: function() {}}
};
function Server() {
this.pretender = new Pretender();
this.map = null;
this.httpServer = http.createServer(this.handleRequest.bind(this));
this.routeDefinitions = [];
}
Server.prototype.routes = function(callback) {
this.map = callback;
this._executeDSL();
};
Server.prototype.start = function(port) {
this.pretender.unhandledRequest = this.unhandledRequest.bind(this);
this.httpServer.listen(port);
};
Server.prototype._executeDSL = function() {
this.map.call(this);
};
function verbify(method) {
return function(url, opts) {
this.addRoute(method, url, opts);
};
}
Server.prototype.get = verbify('GET');
Server.prototype.post = verbify('POST');
Server.prototype.put = verbify('PUT');
Server.prototype['delete'] = verbify('DELETE');
Server.prototype.patch = verbify('PATCH');
Server.prototype.head = verbify('HEAD');
Server.prototype.addRoute = function(method, url, opts) {
var moduleName = opts.from;
var handler = opts.with;
this.routeDefinitions.push({method: method, url: url, module: moduleName, handler: handler});
this.pretender.register(method, url, function() {
var moduleObj = require(path.join(process.cwd(), moduleName));
return moduleObj[handler].apply(moduleObj, arguments);
});
};
Server.prototype.stop = function(port) {
this.pretender.shutdown();
};
Server.prototype.handleRequest = function(request, response) {
var pretenderRequest = new PretenderRequest(request.method, request.url);
pretenderRequest.respond = function(status, headers, body) {
response.statusCode = status;
Object.keys(headers).forEach(function(header) {
response.setHeader(header, headers[header]);
});
response.end(body);
};
var pretenderHandler = this.pretender._handlerFor(request.method, request.url, pretenderRequest);
if (pretenderHandler) {
this.pretender.handleRequest(pretenderRequest);
} else {
response.statusCode = 404;
response.end();
}
};
Server.prototype.unhandledRequest = function(verb, path, request) {
debugger;
};
Server.prototype.toJSON = function() {
return {routes: this.routeDefinitions};
};
module.exports = Server;