-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfront_controller.js
65 lines (58 loc) · 2.06 KB
/
front_controller.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
/**
* Simple front controller and routes manager
* @author Rinat Borovskikh <[email protected]>
*
*/
/**
* Base controller for all project contollers.
* It implements main controller methods, such as render (template render) and send method.
*/
BaseController = function(request, response) {
this.request = request;
this.response = response;
this.render = function(template, vars) {
return this.response.render(template, vars);
};
this.send = function(content) {
return this.response.send(content);
};
};
/**
* "DefineRoute" tries to resolve user request (according urlmanager and decode rules),
* and invokes target request controller and action with request parameters.
*
* If target controller and action were not found, it initializes 404 error response.
*/
exports.DefineRoute = function(app)
{
app.get('*', function(request,response)
{
/* Calls urlmanager.resolve to resolve url */
var resolved = app.settings.urlmanager.resolve(request.url);
if(resolved.controller)
{
/* invoke conroller it exists and start action */
require('fs').exists(__dirname + '/controllers/' + resolved.controller + '.js', function(exists) {
if(exists)
{
var middleware = require('./controllers/' + resolved.controller);
var controller = new middleware.controller(request, response, app, resolved.params);
var action = !resolved.action ? 'indexAction' : resolved.action + 'Action';
if(typeof controller[action] == 'function')
{
controller[action]();
delete controller;
}
}
else
{
app.settings.urlmanager.send404(request, response);
}
});
}
else
{
app.settings.urlmanager.send404(request, response);
}
})
}