-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.js
More file actions
90 lines (73 loc) · 2.47 KB
/
router.js
File metadata and controls
90 lines (73 loc) · 2.47 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
86
87
88
89
90
require('mootools');
var fs = require('fs');
module.exports = new Class({
Implements: [Options],
options: {
config: null
},
routes: {},
initialize: function(options) {
console.log('Xylesoft.component.Router Loaded');
this.setOptions(options);
this.loadConfig();
this.prepareRouteInstances();
console.log(this.routes);
},
loadConfig: function() {
if (this.options.config === null) {
throw new Error('Xylesoft.component.Router: option `config` is NULL');
}
if (! fs.existsSync(this.options.config)) {
throw new Error('Xylesoft.component.Router: can\'t find config file=' + this.options.config);
}
var configObj = JSON.parse(fs.readFileSync(this.options.config));
this.routes = configObj.routes;
this.defaults = configObj.defaults;
},
/**
* Responsible for looking at all the pattern properties in this.routes and converting to Regex instances based on the string.
*/
prepareRouteInstances: function() {
Object.each(this.routes, function(route, name, obj) {
if (route.pattern) {
obj[name].pattern = new RegExp(route.pattern);
}
if (!route.name) {
// give the route a name.
obj[name].name = name;
}
obj[name].httpStatus = 200;
});
},
/**
* Responsible for converting the URL and request to a controller and module.
*/
find: function(request) {
var url = request.url;
var method = request.method;
var route = this.getRoute(url);
// check we have a route, if not throw error404.
route = route || this.defaults.errors[404];
if (! route.methods.contains(method)) {
if (route.name === "error.404") {
return this.defaults.errors[500];
}
return this.defaults.errors[404];
}
// we now have the right controller based on the route and methods.
return route;
},
getRoute: function(url) {
var gotRoute = false;
var foundRoute = null;
Object.each(this.routes, function(route, name, routes) {
if (gotRoute) return;
// Check if pattern matches the URL
if (route.pattern.exec(url)) {
gotRoute = true;
foundRoute = route;
}
});
return foundRoute;
}
});