Permalink
Browse files

More refactoring, finally get all helpers out

  • Loading branch information...
mde
mde committed Apr 19, 2013
1 parent be24547 commit dba239db29650cf06f064c5706bd8e43c9963138
Showing with 171 additions and 155 deletions.
  1. +31 −151 lib/{app.js → app/index.js}
  2. +42 −0 lib/app/logging.js
  3. +92 −0 lib/app/request_helpers.js
  4. +4 −2 lib/controller/init.js
  5. +2 −2 lib/geddy.js
@@ -19,27 +19,23 @@
var domain = require('domain')
, fs = require('fs')
, path = require('path')
- , url = require('url')
, model = require('model')
- , controller = require('./controller')
- , utils = require('./utils')
- , querystring = require('../deps/qs')
+ , controller = require('../controller')
+ , utils = require('../utils')
, cwd = process.cwd()
- , errors = require('./response/errors')
- , response = require('./response')
- , init = require('./init')
- , helpers = require('./template/helpers')
- , actionHelpers = require('./template/helpers/action')
- , BaseController = require('./controller/base_controller').BaseController
- , ErrorController = require('./controller/error_controller').ErrorController
+ , errors = require('../response/errors')
+ , init = require('../init')
+ , helpers = require('../template/helpers')
+ , actionHelpers = require('../template/helpers/action')
+ , ErrorController = require('../controller/error_controller').ErrorController
, StaticFileController =
- require('./controller/static_file_controller').StaticFileController
- , sessions = require('./sessions')
- , Request = require('./request').Request
- , Response = response.Response
- , InFlight = require('./in_flight').InFlight
+ require('../controller/static_file_controller').StaticFileController
+ , controllerInit = require('../controller/init')
+ , InFlight = require('../in_flight').InFlight
+ , sessions = require('../sessions')
, usingCoffee // Global variable for CoffeeScript
- , controllerInit = require('./controller/init')
+ , logging = require('./logging')
+ , requestHelpers = require('./request_helpers');
// Set up a bunch of aliases
geddy.inFlight = new InFlight();
@@ -77,7 +73,7 @@ var App = function () {
// ==================
, _registerTemplatePaths = function (next) {
var viewsPath = path.normalize('app/views')
- , geddyTemplatesPath = path.join(__dirname, 'template', 'templates');
+ , geddyTemplatesPath = path.join(__dirname, '../template', 'templates');
// If viewsPath doesn't exist they're running viewless
if(!utils.file.existsSync(viewsPath)) {
@@ -221,130 +217,9 @@ var App = function () {
try {
require(path.join(cwd, 'config', 'after_start'));
} catch (e) {}
- }
-
- , getUrl = function (req) {
- var reqUrl = req.url;
- // Sanitize URL; reduce multiple slashes to single slash
- reqUrl = reqUrl.replace(/\/{2,}/g, '/');
- // Strip trailing slash for the purpose of looking for a matching
- // route (will still check for directory + index on statics)
- // Don't strip if the entire path is just '/'
- reqUrl = reqUrl.replace(/(.+)\/$/, '$1');
- return reqUrl;
- }
-
- , getUrlParams = function (reqUrl) {
- return url.parse(reqUrl, true).query;
- }
-
- , getMethod = function (reqUrl, urlParams, req) {
- var method;
- 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();
- return method;
- }
-
- , enhanceRequest = function (req) {
- var reqObj;
- // TODO Replace this with readable-stream module for 0.8 support
- // Buffered request-obj -- buffer the request data,
- // and pass this proxy object to the controller
- if (typeof req.read != 'function') {
- reqObj = new Request(req);
- }
- // Not needed for 0.10
- else {
- reqObj = req;
- // Shim, method for so-called Connect-style middleware
- reqObj.query = Request.parseQuery(req.url);
- }
- return reqObj;
- }
-
- , enhanceResponse = function (resp) {
- return new Response(resp);
- }
-
- , getAccessTime = function () {
- return (new Date()).getTime()
- }
-
- // Domains-based error-handling should make this less necessary
- , initInFlight = function (reqObj, respObj, method, accessTime) {
- var inFlightId = geddy.inFlight.addEntry({
- request: reqObj
- , method: method
- , response: respObj
- , accessTime: accessTime
- });
- reqObj._geddyId = inFlightId;
- respObj._geddyId = inFlightId;
- }
-
- // This function requires the geddy global
- // for log and inFlight
- , initRequestLogging = function (reqUrl, reqObj, respObj, method, accessTime) {
- // Probably should proxy events for wrapped Response obj
- respObj.resp.addListener('finish', function () {
- var id = respObj._geddyId
- , stat = respObj.resp.statusCode
- , level = parseInt(stat, 10)
- , logMsg;
-
- // Status code representation for logging
- if (level > 499) {
- level = 'error';
- }
- else level = 'access';
-
- // Apache extended log-format
- // TODO: Allow customizing this format
- logMsg = reqObj.connection.remoteAddress + ' ' +
- '- ' +
- '- ' +
- '[' + new Date(accessTime) + '] ' +
- '"' + method + ' ' + reqUrl + ' ' +
- reqObj.httpVersion + '" ' +
- stat + ' ' +
- (respObj.resp._length || '-') + ' ' +
- '"' + encodeURI(reqObj.headers['referer'] || '-') + '" ' +
- '"' + (reqObj.headers['user-agent'] || '-') + '"';
-
- try {
- geddy.log[level](logMsg);
- }
- catch(e) {
- geddy.log.error('Logging failed for request, id ' + id);
- }
-
- geddy.inFlight.removeEntry(id);
- });
- }
-
- , getParams = function (router, reqUrl, method) {
- var params = router.first(reqUrl, method);
- params.controller = utils.string.camelize(params.controller,
- {initialCap: true});
- return params;
};
+
this.router = null;
this.modelRegistry = {};
this.templateRegistry = {};
@@ -386,8 +261,9 @@ var App = function () {
, 'session'
];
+ // Mix all the shits onto the controller instance
utils.mixin(controllerInst, {
- app: this
+ app: this
, url: reqUrl
, method: method
, params: params
@@ -526,8 +402,8 @@ var App = function () {
dmn.add(req);
dmn.add(resp);
- reqObj = enhanceRequest(req);
- respObj = enhanceResponse(resp);
+ reqObj = requestHelpers.enhanceRequest(req);
+ respObj = requestHelpers.enhanceResponse(resp);
dmn.on('error', function (err) {
errors.respond(err, respObj);
@@ -544,16 +420,20 @@ var App = function () {
, params
, controllerInst;
- reqUrl = getUrl(req);
- urlParams = getUrlParams(reqUrl);
- method = getMethod(reqUrl, urlParams, req);
- accessTime = getAccessTime();
+ // Parse out some needed request properties
+ reqUrl = requestHelpers.getUrl(req);
+ urlParams = requestHelpers.getUrlParams(reqUrl);
+ method = requestHelpers.getMethod(reqUrl, urlParams, req);
+ accessTime = requestHelpers.getAccessTime();
+
+ // Now only for timeout, domains are handling errors
+ requestHelpers.initInFlight(reqObj, respObj, method, accessTime);
- initInFlight(reqObj, respObj, method, accessTime);
- initRequestLogging(reqUrl, reqObj, respObj, method, accessTime);
+ // TODO: Allow custom formats
+ logging.initRequestLogger(reqUrl, reqObj, respObj, method, accessTime);
- params = getParams(self.router, reqUrl, method);
- // Route/method combo gives us something valid
+ params = requestHelpers.getParams(self.router, reqUrl, method);
+ // Route/method combo give us something valid?
if (params) {
controllerInst = controller.create(params.controller);
View
@@ -0,0 +1,42 @@
+
+var logging = {
+ initRequestLogger: function (reqUrl, reqObj, respObj, method, accessTime) {
+ // Probably should proxy events for wrapped Response obj
+ respObj.resp.addListener('finish', function () {
+ var id = respObj._geddyId
+ , stat = respObj.resp.statusCode
+ , level = parseInt(stat, 10)
+ , logMsg;
+
+ // Status code representation for logging
+ if (level > 499) {
+ level = 'error';
+ }
+ else level = 'access';
+
+ // Apache extended log-format
+ // TODO: Allow customizing this format
+ logMsg = reqObj.connection.remoteAddress + ' ' +
+ '- ' +
+ '- ' +
+ '[' + new Date(accessTime) + '] ' +
+ '"' + method + ' ' + reqUrl + ' ' +
+ reqObj.httpVersion + '" ' +
+ stat + ' ' +
+ (respObj.resp._length || '-') + ' ' +
+ '"' + encodeURI(reqObj.headers['referer'] || '-') + '" ' +
+ '"' + (reqObj.headers['user-agent'] || '-') + '"';
+
+ try {
+ geddy.log[level](logMsg);
+ }
+ catch(e) {
+ geddy.log.error('Logging failed for request, id ' + id);
+ }
+
+ geddy.inFlight.removeEntry(id);
+ });
+ }
+};
+
+module.exports = logging;
View
@@ -0,0 +1,92 @@
+var url = require('url')
+ , utils = require('utilities')
+ , Request = require('../request').Request
+ , Response = require('../response').Response
+ , InFlight = require('../in_flight').InFlight;
+
+var requestHelpers = {
+ getUrl: function (req) {
+ var reqUrl = req.url;
+ // Sanitize URL; reduce multiple slashes to single slash
+ reqUrl = reqUrl.replace(/\/{2,}/g, '/');
+ // Strip trailing slash for the purpose of looking for a matching
+ // route (will still check for directory + index on statics)
+ // Don't strip if the entire path is just '/'
+ reqUrl = reqUrl.replace(/(.+)\/$/, '$1');
+ return reqUrl;
+ }
+
+, getUrlParams: function (reqUrl) {
+ return url.parse(reqUrl, true).query;
+ }
+
+, getMethod: function (reqUrl, urlParams, req) {
+ var method;
+ 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();
+ return method;
+ }
+
+, enhanceRequest: function (req) {
+ var reqObj;
+ // TODO Replace this with readable-stream module for 0.8 support
+ // Buffered request-obj -- buffer the request data,
+ // and pass this proxy object to the controller
+ if (typeof req.read != 'function') {
+ reqObj = new Request(req);
+ }
+ // Not needed for 0.10
+ else {
+ reqObj = req;
+ // Shim, method for so-called Connect-style middleware
+ reqObj.query = Request.parseQuery(req.url);
+ }
+ return reqObj;
+ }
+
+, enhanceResponse: function (resp) {
+ return new Response(resp);
+ }
+
+, getAccessTime: function () {
+ return (new Date()).getTime()
+ }
+
+// Domains-based error-handling should make this less necessary
+, initInFlight: function (reqObj, respObj, method, accessTime) {
+ var inFlightId = geddy.inFlight.addEntry({
+ request: reqObj
+ , method: method
+ , response: respObj
+ , accessTime: accessTime
+ });
+ reqObj._geddyId = inFlightId;
+ respObj._geddyId = inFlightId;
+ }
+
+, getParams: function (router, reqUrl, method) {
+ var params = router.first(reqUrl, method);
+ params.controller = utils.string.camelize(params.controller,
+ {initialCap: true});
+ return params;
+ }
+};
+
+module.exports = requestHelpers;
+
View
@@ -1,4 +1,5 @@
var utils = require('utilities')
+ , querystring = require('../../deps/qs')
, sessions = require('../sessions')
, CookieCollection = require('../cookies').CookieCollection
, i18n = utils.i18n
@@ -26,7 +27,8 @@ init = {
}
, parseBody: function (cb) {
- var body = ''
+ var self = this
+ , body = ''
, bodyParams
, reqObj = this.request
, contentType = reqObj.headers['content-type'];
@@ -65,7 +67,7 @@ init = {
catch (e) {}
}
- geddy.mixin(this.params, bodyParams);
+ geddy.mixin(self.params, bodyParams);
reqObj.body = body;
Oops, something went wrong.

0 comments on commit dba239d

Please sign in to comment.