forked from geddy/geddy
/
app.js
478 lines (436 loc) · 15.2 KB
/
app.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/*
* Geddy JavaScript Web development framework
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var fs = require('fs')
, url = require('url')
, querystring = require('../deps/qs')
, path = require('path')
, cwd = process.cwd()
, errors = require('./errors')
, response = require('./response')
, model = require('./model')
, utils = require('./utils/index')
, fileUtils = require('./utils/file')
, inflection = require('../deps/inflection')
, i18n = require('./i18n')
, init = require('./init')
, FunctionRouter = require('./routers/function_router').FunctionRouter
, RegExpRouter = require('./routers/regexp_router').RegExpRouter
, BaseController = require('./base_controller').BaseController
, sessions = require('./sessions')
, CookieCollection = require('./cookies').CookieCollection
, Request = require('./request').Request
, InFlight = require('./in_flight').InFlight;
// Set up a bunch of aliases
geddy.FunctionRouter = FunctionRouter;
geddy.RegExpRouter = RegExpRouter;
geddy.inFlight = new InFlight();
geddy.inflection = inflection;
geddy.model = model;
geddy.utils = utils;
var App = function () {
var JSPAT = /\.js$/;
var _getDirList = function (dirname) {
var dirList = fs.readdirSync(dirname)
, fileName
, filePath
, ctorName
, ret = [];
for (var i = 0; i < dirList.length; i++) {
fileName = dirList[i];
// Any files ending in '.js' -- e.g., 'neil_pearts.js'
if (JSPAT.test(fileName)) {
// Strip the '.js', e.g., 'neil_pearts'
fileName = fileName.replace(JSPAT, '');
// Convert underscores to camelCase with
// initial cap, e.g., 'NeilPearts'
ctorName = geddy.string.camelize(fileName, true);
filePath = path.join(cwd, dirname, fileName);
ret.push({
ctorName: ctorName
, filePath: filePath
});
}
}
return ret;
}
// Load models
// ==================
, _registerModels = function (next) {
var modelDir = 'app/models'
, dirList
, item;
// May be running entirely model-less
if (!path.existsSync(path.join(cwd, modelDir))) {
next();
}
else {
dirList = _getDirList(modelDir)
// Dynamically create controller
// constructors from files in app/models
for (var i = 0; i < dirList.length; i++) {
item = dirList[i];
require(item.filePath);
}
next();
}
}
// Load controller ctors
// ==================
, _registerConstructors = function (next) {
var controllerDir = 'app/controllers'
, dirList = _getDirList(controllerDir)
, item
, ctors = {}
, ctor;
// Dynamically create controller constructors
// from files in app/constructors
for (var i = 0; i < dirList.length; i++) {
item = dirList[i];
ctor = require(item.filePath)[item.ctorName];
ctor.origPrototype = ctor.prototype;
this.controllerRegistry[item.ctorName] = ctor;
}
next();
}
// Load the router
// ==================
, _loadRouter = function (next) {
router = require(path.join(cwd, '/config/router'));
router = router.router || router;
this.router = router;
next();
}
// Connect to session-store
// ==================
, _loadSessionStore = function (next) {
sessionsConfig = geddy.config.sessions;
if (sessionsConfig) {
sessions.createStore(sessionsConfig.store, next);
}
else {
next();
}
}
// Load any locales, set the default
// ==================
, _loadLocales = function (next) {
init.init(next);
}
// Load metrics if they're turned on
// ==================
, _loadMetrics = function (next) {
if (geddy.config.metrics) {
geddy.metrics = require('./metric');
}
next();
}
// Register template-paths
// ==================
, _registerTemplatePaths = function (next) {
var viewsPath = path.normalize('app/views');
// May be running entirely viewless
if (!path.existsSync(viewsPath)) {
this.templateRegistry = {};
next();
}
else {
var templates = {}
, files
, file
, pat = /\.ejs$/;
files = fileUtils.readdirR(viewsPath);
for (var i = 0; i < files.length; i++) {
file = files[i];
if (pat.test(file)) {
templates[file] = true;
}
}
this.templateRegistry = templates;
next();
}
}
// Run code in the app's config/init.js
// ==================
, _runAppLocalInit = function (next) {
var initPath = path.join(cwd, 'config/init.js');
if (path.existsSync(initPath)) {
require(initPath);
}
next();
};
this.router = null;
this.modelRegistry = {};
this.templateRegistry = {};
this.controllerRegistry = {};
this.init = function (callback) {
var self = this
, items
, chain;
items = [
_registerModels
, _registerConstructors
, _loadRouter
, _loadSessionStore
, _loadLocales
, _loadMetrics
, _registerTemplatePaths
, _runAppLocalInit
];
chain = new geddy.async.SimpleAsyncChain(items, this);
chain.last = function () {
self.start(callback);
};
chain.run();
};
this.start = function (callback) {
var self = this
, ctors = this.controllerRegistry
, router = this.router;
// Handle the requests
// ==================
var allRequestTimer = geddy.config.metrics && geddy.metrics.Timer('Geddy.all-requests')
, controllerActionTimers = {};
geddy.server.addListener('request', function (req, resp) {
var reqObj
, params
, urlParams
, method
, ctor
, appCtor
, baseController
, controller
, controllerName
, actionName
, staticPath
, staticResp
, err
, errResp
, body = ''
, bodyParams
, steps = {
parseBody: false
, sessions: false
}
, finish
, accessTime = (new Date()).getTime()
, inFlighId;
// Buffered request-obj -- buffer the request data,
// and pass this proxy object to the controller
reqObj = new Request(req);
finish = function (step) {
steps[step] = true;
for (var p in steps) {
if (!steps[p]) {
return false;
}
}
controller._handleAction.call(controller, params.action);
reqObj.sync(); // Flush buffered events and begin emitting
};
if (router) {
urlParams = url.parse(req.url, true).query;
if (req.method.toUpperCase() == 'POST') {
// POSTs may be overridden by the _method param
if (urlParams._method) {
method = urlParams._method;
}
// Or x-http-method-override header
else if (req.headers['x-http-method-override']) {
method = req.headers['x-http-method-override'];
}
else {
method = req.method;
}
}
else {
method = req.method;
}
// Okay, let's be anal and force all the HTTP verbs to uppercase
method = method.toUpperCase();
inFlightId = geddy.inFlight.addEntry({
request: req
, method: method
, response: resp
, accessTime: accessTime
});
req._geddyId = inFlightId;
resp._geddyId = inFlightId;
// FIXME: Holy shit, all inline here
resp.addListener('finish', function () {
var id = resp._geddyId
, entry = geddy.inFlight.getEntry(id)
, req = entry.request
, stat = resp.statusCode
, level = parseInt(stat, 10) > 499 ? 'error' : 'access'
, endTime = new Date();
// Apache extended log-format
geddy.log[level](req.connection.remoteAddress + ' ' +
'- ' +
'- ' +
'[' + new Date(entry.accessTime) + '] ' +
'"' + entry.method + ' ' + req.url + ' ' +
req.httpVersion + '" ' +
stat + ' ' +
(resp._length || '-') + ' ' +
'"' + (req.headers['referer'] || '-') + '" ' +
'"' + (req.headers['user-agent'] || '-') + '" ');
geddy.inFlight.removeEntry(id);
if (geddy.config.metrics) {
allRequestTimer.update(endTime - accessTime);
controllerActionTimers[controllerName] = controllerActionTimers[controller] || {}
controllerActionTimers[controllerName][actionName] =
controllerActionTimers[controllerName][actionName] ||
geddy.metrics.Timer("Geddy."+controllerName + '.' + actionName)
controllerActionTimers[controllerName][actionName].update(endTime - accessTime);
}
});
params = router.first(req, method);
}
if (params) {
if (params instanceof Error) {
err = new errors.MethodNotAllowedError(method + ' method is not allowed.');
errResp = new response.Response(resp);
errResp.send(err.message, err.statusCode, {
'Content-Type': 'text/html'
, 'Allow': params.allowed.join(', ')
});
}
else {
controllerName = params.controller;
actionName = params.action;
ctor = ctors[params.controller];
if (ctor) {
// Merge params from the URL and the query-string to produce a
// Grand Unified Params object
geddy.mixin(params, urlParams);
// If it's a plain form-post, save the request-body, and parse it into
// params as well
if ((req.method == 'POST' || req.method == 'PUT') &&
(req.headers['content-type'] &&
(req.headers['content-type'].indexOf('form-urlencoded') > -1 ||
req.headers['content-type'].indexOf('application/json') > -1))) {
req.addListener('data', function (data) {
body += data.toString();
});
// Handle the request once it's finished
req.addListener('end', function () {
bodyParams = querystring.parse(body);
geddy.mixin(params, bodyParams);
req.body = body;
finish('parseBody');
});
}
else {
finish('parseBody');
}
// If there's an Application controller, use an instance of it
// as the prototype of the controller for this request
if (ctors.Application) {
// The constructor for the Application controller
appCtor = ctors.Application;
// Give the constructor a new prototype to inherit from: an instance
// of the BaseController, with the methods/properties from its original
// prototype copied over
appCtor.prototype = utils.enhance(new BaseController(),
appCtor.origPrototype);
// Make an instance -- this instance will be the proto for the
// controller for this request
baseController = new appCtor();
}
// If there's no Application controller, use an instance of
// BaseController as the proto
else {
baseController = new BaseController();
}
// Give the constructor for this request's controller a new
// prototype: the Application/BaseController (or just BaseController)
// instance, with the methods/properties from the original prototype
// copied over
ctor.prototype = utils.enhance(baseController,
ctor.origPrototype);
// Instantiate the controller
controller = new ctor();
// Now that there's a controller, record the access-time
controller.accessTime = accessTime;
if (typeof controller[params.action] == 'function') {
controller.app = self;
controller.request = reqObj;
controller.response = resp;
controller.method = method;
controller.params = params;
controller.name = params.controller;
controller.i18n = new i18n.I18n(controller);
// We have a controller instance; register it with the
// in-flight data
geddy.inFlight.updateEntry(req._geddyId, {
controller: controller
});
controller.cookies = new CookieCollection(req);
if (geddy.config.sessions) {
controller.session =
new sessions.Session(controller, function () {
finish('sessions');
});
}
else {
finish('sessions');
}
}
// No action, 500 error
else {
err = new errors.InternalServerError('No ' + params.action +
' action on ' + params.controller + ' controller.');
errResp = new response.Response(resp);
errResp.send(err.message, err.statusCode,
{'Content-Type': 'text/html'});
}
}
// no controller, 500 error
else {
err = new errors.internalservererror('controller ' +
params.controller + ' not found.');
errresp = new response.response(resp);
errresp.send(err.message, err.statuscode,
{'content-type': 'text/html'});
}
}
}
// Either static or 404
else {
// Get the path to the file
staticPath = geddy.config.staticFilePath + '/' + req.url;
// Ignore querystring
staticPath = staticPath.split('?')[0];
// Decode path (e.g. %20)
staticPath = decodeURIComponent(staticPath);
if (path.existsSync(staticPath)) {
staticResp = new response.Response(resp);
staticResp.sendFile(staticPath);
}
else {
err = new errors.NotFoundError(req.url + ' not found.');
errResp = new response.Response(resp);
errResp.send(err.message, err.statusCode,
{'Content-Type': 'text/html'});
}
}
});
callback();
};
};
module.exports.App = App;