-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathframework.js
188 lines (163 loc) · 5.28 KB
/
framework.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// REST Framework
"use strict";
var http = require("http"),
fs = require('fs'),
qs = require('querystring'),
url = require('url'),
path = require("path"),
root = __dirname;
var appFramework = function(){ /*empty function*/ };
// Contains all HTTP message handlers.
appFramework.handlerCollection = [];
appFramework.prototype.config = {
controllerPath: path.join(root + "/controllers"),
handlerPath: path.join(root + "/handlers"),
skipMessageHandlers: false
};
appFramework.prototype.sendJSON = function(obj){
var that = this;
that.response.activeHandlerCollection.forEach(function(handler, index){
handler.handleResponse.call(that, that.request, that.response);
});
// Send the response in JSON format
// Enabling CORS for all Origins.
that.response.setHeader("Access-Control-Allow-Origin", "*");
that.response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
that.response.setHeader("Access-Control-Allow-Headers", "Content-Type");
that.response.end(JSON.stringify(obj, null, '\t'));
};
appFramework.prototype.initLoad = function(){
console.log("InitLoad InProgress...");
var controllerPath = this.config.controllerPath,
handlerPath = this.config.handlerPath;
if(fs.existsSync(controllerPath)){
fs.readdir(controllerPath, function(error, files){
files.forEach(function(file, index, files){
require(path.join(controllerPath + '/' + file));
});
});
} else {
response.statusCode = 404;
response.end(http.STATUS_CODES['404']);
}
// Initialize all handlers here
if(fs.existsSync(handlerPath)){
fs.readdir(handlerPath, function(error, files){
files.forEach(function(file, index, files){
appFramework.handlerCollection.push(require(path.join(handlerPath + '/' + file)));
});
});
} else {
response.statusCode = 404;
response.end(http.STATUS_CODES['404']);
}
console.log("InitLoad Done...");
};
appFramework.prototype.getRequestPayload = function(callback){
// extract the GET and POST payload data and pass it to the action CB
var req = this.request,
res = this.response;
if(!!req){
var parsedPayload;
switch(req.method){
case 'GET':
parsedPayload = qs.parse(url.parse(req.url).query);
callback(parsedPayload);
//return query;
break;
case 'POST':
var payload = '';
req.setEncoding("utf8"); // set encoding
req.on("data", function(chunk){
payload+=chunk;
console.log("payload : "+chunk);
});
req.on("end", function(){
//console.log(payload);
parsedPayload = qs.parse(payload);
callback(parsedPayload);
});
break;
}
}
};
appFramework.prototype.startServer = function(port){
var that = this,
route = new router(); // Get the file server root directory path
// Request pipeline starts here.
http.createServer(function(request, response){
try{
if(!!request){
console.log(request.url);
var parsedUrl = url.parse(request.url),
routeFound = false;
response.activeHandlerCollection = [];
//console.log("Url : "+parsedUrl.pathname);
that.request = request;
that.response = response;
that.httpStatusCodes = http.STATUS_CODES;
//Pipeline#1: HTTP Message Handlers (Global).
if(!that.config.skipMessageHandlers){
// Request must pass through all defined handlers.
appFramework.handlerCollection.forEach(function(handler, index){
handler.handleRequest.call(that, request, response);
response.activeHandlerCollection.unshift(handler);
});
};
route.findRouteByRequest.call(that, parsedUrl, function(error, data){
if(error) {
console.log(data.message);
// We skip the [OPTIONS] requests.
// End Response here if its a preflight request or Invalid route.
that.response.statusCode = data.statusCode;
that.sendJSON(that.httpStatusCodes[data.statusCode]);
return;
}
// data contains callback function and optional params
/*
Now check for two things:
1. Authentication(Form only)
2. Request handlers per route
*/
if(!!data && !!data.attr && !!data.handler){
appFramework.handlerCollection.forEach(function(handler, index){
if(data.handler.toLowerCase() === handler.handlerName.toLowerCase()){
handler.handleRequest.call(that, request, response);
response.activeHandlerCollection.unshift(handler);
return;
}
});
}
if(!!data){
// Get the request payload if there
that.getRequestPayload(function(payload){
var uriParam = data.param,
args;
//console.log("Test: "+payload);
if(!!payload){
switch(that.request.method){
case 'GET':
// format the qs object to array
args = Object.keys(payload).map(function(key){ return payload[key]; });
console.log(args);
break;
case 'POST':
args = uriParam === undefined ? [payload]: [uriParam, payload];
console.log(payload);
break;
}
// Call controller action callback with args
data.actionCb.apply(that, args);
}
});
}
});
}
}catch(ex){
that.response.statusCode = 500;
that.sendJSON(that.httpStatusCodes[500]);
}
}).listen(port);
console.log("Server started...");
};
module.exports = new appFramework();