Skip to content
Browse files

some cleanup and indentation fix

  • Loading branch information...
1 parent f87a230 commit 4a6b7af16f04b2cfc6cf0819bc7c806ad1e08f7f @Shogun147 committed Jan 8, 2014
Showing with 564 additions and 619 deletions.
  1. +1 −0 .npmignore
  2. +0 −2 lib/cli-args.js
  3. +103 −103 lib/katana.js
  4. +90 −90 lib/request.js
  5. +273 −273 lib/response.js
  6. +78 −78 lib/router.js
  7. +5 −5 lib/session/memory.js
  8. +9 −9 lib/session/redis.js
  9. +0 −49 modules.json
  10. +1 −3 template/app.js
  11. +4 −7 template/app/config/development/app.js
View
1 .npmignore
@@ -3,3 +3,4 @@
npm-debug.log
test/
examples/
+todo.md
View
2 lib/cli-args.js
@@ -49,5 +49,3 @@ cmd.httpsPort && App.set('https port', cmd.httpsPort);
cmd.httpsKey && App.set('https key', cmd.httpsKey);
cmd.httpsCert && App.set('https cert', cmd.httpsCert);
cmd.httpsCa && App.set('https ca', cmd.httpsCa);
-
-
View
206 lib/katana.js
@@ -36,9 +36,9 @@ App.middlewares = {};
App.settings = {};
App._modules = ['app'].concat(
- Object.keys(App.info.katana.modules).filter(function(name) {
- return App.info.katana.modules[name].enabled;
- })
+ Object.keys(App.info.katana.modules).filter(function(name) {
+ return App.info.katana.modules[name].enabled;
+ })
);
App.resolve = function(path) {
@@ -72,7 +72,7 @@ function resolveKey(path) {
}
App.get = function(key) {
- if (!key) { return this.settings; }
+ if (!key) { return this.settings; }
var path = resolveKey(key).split('/');
var target = this.settings[path.shift()];
@@ -82,17 +82,17 @@ App.get = function(key) {
}
while(path.length > 0) {
- key = path.shift();
+ key = path.shift();
- if (target && target.hasOwnProperty(key)) {
- target = target[key];
- continue;
- }
+ if (target && target.hasOwnProperty(key)) {
+ target = target[key];
+ continue;
+ }
- return undefined;
+ return undefined;
}
- return target;
+ return target;
}
App.set = function(key, value) {
@@ -104,13 +104,13 @@ App.set = function(key, value) {
if (!path.length) { return false; }
while(path.length > 1) {
- key = path.shift();
+ key = path.shift();
- if (typeof(target[key]) !== 'object') {
- target[key] = {};
- }
+ if (typeof(target[key]) !== 'object') {
+ target[key] = {};
+ }
- target = target[key];
+ target = target[key];
}
key = path.shift();
@@ -120,40 +120,40 @@ App.set = function(key, value) {
}
App.enable = function(key) {
- this.set(key, true);
+ this.set(key, true);
}
App.disable = function(key) {
- this.set(key, false);
+ this.set(key, false);
}
App.enabled = function(key) {
- return !!this.get(key);
+ return !!this.get(key);
}
App.disabled = function(key) {
- return !this.get(key);
+ return !this.get(key);
}
App.readConf = function(env) {
- var self = this;
+ var self = this;
- env = env || 'development';
+ env = env || 'development';
- self._modules.forEach(function(module) {
- var dir = self.root + (module==='app' ? 'app' : 'modules/'+ module) +'/config/';
+ self._modules.forEach(function(module) {
+ var dir = self.root + (module==='app' ? 'app' : 'modules/'+ module) +'/config/';
- if (Fs.existsSync(dir + env) && Fs.statSync(dir + env).isDirectory()) {
- Fs.readdirSync(dir + env).forEach(function(file) {
- if (Path.extname(file) !== '.js' && Path.extname(file) !== '.json') { return; }
+ if (Fs.existsSync(dir + env) && Fs.statSync(dir + env).isDirectory()) {
+ Fs.readdirSync(dir + env).forEach(function(file) {
+ if (Path.extname(file) !== '.js' && Path.extname(file) !== '.json') { return; }
- var name = Path.basename(file, Path.extname(file));
- var conf = require(dir + env +'/'+ file);
+ var name = Path.basename(file, Path.extname(file));
+ var conf = require(dir + env +'/'+ file);
- self.set(module +':'+ name, (env==='development' ? conf : merge(self.get(module +':'+ name), conf)));
- });
- }
- });
+ self.set(module +':'+ name, (env==='development' ? conf : merge(self.get(module +':'+ name), conf)));
+ });
+ }
+ });
}
App.readConf(); (App.env !== 'development') && App.readConf(App.env);
@@ -164,38 +164,38 @@ var Request = require('./request');
var Response = require('./response');
App.start = function() {
- var http = this.get('http');
- var https = this.get('https');
+ var http = this.get('http');
+ var https = this.get('https');
var wait = !!http + !!https;
- if (http) {
- var httpHost = http.host || '127.0.0.1';
- var httpPort = http.port || 8000;
+ if (http) {
+ var httpHost = http.host || '127.0.0.1';
+ var httpPort = http.port || 8000;
- this.http = Http.createServer(wrapRequest);
- this.http.listen(httpPort, httpHost, function() {
- console.log('Katana HTTP server on:', httpHost +':'+ httpPort);
+ this.http = Http.createServer(wrapRequest);
+ this.http.listen(httpPort, httpHost, function() {
+ console.log('Katana HTTP server on:', httpHost +':'+ httpPort);
(!--wait) && App.emit('ready');
- });
- }
+ });
+ }
- if (https) {
- var httpsHost = https.host || '127.0.0.1';
- var httpsPort = https.port || 443;
+ if (https) {
+ var httpsHost = https.host || '127.0.0.1';
+ var httpsPort = https.port || 443;
- this.https = Https.createServer({
- key: https.key || null,
- cert: https.cert || null,
- ca: https.ca || null
- }, wrapRequest);
- this.https.listen(httpsPort, httpsHost, function() {
- console.log('Katana HTTPS server on:', httpsHost +':'+ httpsPort);
+ this.https = Https.createServer({
+ key: https.key || null,
+ cert: https.cert || null,
+ ca: https.ca || null
+ }, wrapRequest);
+ this.https.listen(httpsPort, httpsHost, function() {
+ console.log('Katana HTTPS server on:', httpsHost +':'+ httpsPort);
(!--wait) && App.emit('ready');
- });
- }
+ });
+ }
}
function wrapRequest(request, response) {
@@ -231,23 +231,23 @@ if (staticsEnabled) {
}
App.handleRequest = function(request, response) {
- var self = this;
+ var self = this;
- if (request.url === '/favicon.ico') {
+ if (request.url === '/favicon.ico') {
request.url = self.get('favicon') || 'public/images/favicon.ico';
- }
+ }
- request.__proto__ = Request;
- response.__proto__ = Response;
+ request.__proto__ = Request;
+ response.__proto__ = Response;
- request.response = response;
- response.request = request;
+ request.response = response;
+ response.request = request;
- request.originalUrl = request.url;
- request.url = utils.decodeURI(request.url);
- request.parsedUrl = Url.parse(request.url);
- request.path = sanitize(request.parsedUrl.pathname).trim('\\s\/');
- request.query = request.parsedUrl.query ? parseQuery(request.parsedUrl.query) : {};
+ request.originalUrl = request.url;
+ request.url = utils.decodeURI(request.url);
+ request.parsedUrl = Url.parse(request.url);
+ request.path = sanitize(request.parsedUrl.pathname).trim('\\s\/');
+ request.query = request.parsedUrl.query ? parseQuery(request.parsedUrl.query) : {};
request.data = {};
request.files = {};
@@ -258,50 +258,50 @@ App.handleRequest = function(request, response) {
request.route = self.router.route(request.path, request.method);
if (request.module !== 'app') {
- // var params = request.route.params;
- // request.originalRoute = request.route;
+ // var params = request.route.params;
+ // request.originalRoute = request.route;
- request.route = self.router.route(request.route.routed, request.method, request.module);
- // route.params = merge(params, route.params);
+ request.route = self.router.route(request.route.routed, request.method, request.module);
+ // route.params = merge(params, route.params);
}
- self.callMiddlewares(request, response, function(error) {
- if (error) {
- // return response.send(error);
- response.writeHead(500, { 'Content-Type': 'text/plain' });
- response.end(error);
- return;
- }
+ self.callMiddlewares(request, response, function(error) {
+ if (error) {
+ // return response.send(error);
+ response.writeHead(500, { 'Content-Type': 'text/plain' });
+ response.end(error);
+ return;
+ }
- self.handle(request, response);
- });
+ self.handle(request, response);
+ });
}
var controller404 = App.get(':routing _404 controller') || 'home';
var action404 = App.get(':routing _404 action') || '_404';
App.handle = function(request, response) {
- var self = this;
- var controller = self.controllers[request.module +'/'+ request.directory + request.controller];
- var _404 = false;
-
- if (!controller) {
- controller = self.controllers['app/'+ controller404];
- _404 = true;
- }
-
- if (controller) {
- var method = _404 ? controller[action404] : (controller[request.action] || controller._call || controller[action404]);
-
- if (typeof(method) === 'function') {
- method = method.bind(controller);
- method(request, response);
- } else {
- response.send(404, 'action not found');
- }
- } else {
- response.send(404, 'controller not found');
- }
+ var self = this;
+ var controller = self.controllers[request.module +'/'+ request.directory + request.controller];
+ var _404 = false;
+
+ if (!controller) {
+ controller = self.controllers['app/'+ controller404];
+ _404 = true;
+ }
+
+ if (controller) {
+ var method = _404 ? controller[action404] : (controller[request.action] || controller._call || controller[action404]);
+
+ if (typeof(method) === 'function') {
+ method = method.bind(controller);
+ method(request, response);
+ } else {
+ response.send(404, 'action not found');
+ }
+ } else {
+ response.send(404, 'controller not found');
+ }
}
App.use = function(type, fn) {
@@ -313,11 +313,11 @@ App.use = function(type, fn) {
}
App.callMiddlewares = function(request, response, done) {
- var self = this;
+ var self = this;
var index = 0;
if (!this.middlewares._.length) {
- return done();
+ return done();
}
function next(request, response) {
View
180 lib/request.js
@@ -8,238 +8,238 @@ var parseRanges = utils.parseRanges;
var fresh = utils.fresh;
var request = module.exports = {
- __proto__: Http.IncomingMessage.prototype
+ __proto__: Http.IncomingMessage.prototype
};
request.__defineGetter__('res', function() {
- return this.response;
+ return this.response;
});
request.__defineGetter__('module', function() {
- return this.route ? this.route.module : undefined;
+ return this.route ? this.route.module : undefined;
});
request.__defineGetter__('directory', function() {
- return this.route ? this.route.directory : undefined;
+ return this.route ? this.route.directory : undefined;
});
request.__defineGetter__('dir', function() {
- return this.route ? this.route.directory : undefined;
+ return this.route ? this.route.directory : undefined;
});
request.__defineGetter__('controller', function() {
- return this.route ? this.route.controller : undefined;
+ return this.route ? this.route.controller : undefined;
});
request.__defineGetter__('action', function() {
- return this.route ? this.route.action : undefined;
+ return this.route ? this.route.action : undefined;
});
request.__defineGetter__('arguments', function() {
- return this.route ? this.route.arguments : undefined;
+ return this.route ? this.route.arguments : undefined;
});
request.__defineGetter__('params', function() {
- return this.route ? this.route.params : undefined;
+ return this.route ? this.route.params : undefined;
});
request.__defineGetter__('routedUrl', function() {
- return this.route ? this.route.routed : undefined;
+ return this.route ? this.route.routed : undefined;
});
request.__defineGetter__('body', function() {
- return this.data;
+ return this.data;
});
request.__defineSetter__('body', function(value) {
- return this.data = value;
+ return this.data = value;
});
request.get = request.header = function(name) {
name = name.toLowerCase();
if (name==='referer' || name==='referrer') {
- return (this.headers.referrer || this.headers.referer);
+ return (this.headers.referrer || this.headers.referer);
}
return this.headers[name];
}
request.accepts = function(type) {
- var args = arguments.length > 1 ? [].slice.apply(arguments) : type;
+ var args = arguments.length > 1 ? [].slice.apply(arguments) : type;
- return utils.accepts(args, this.get('accept'));
+ return utils.accepts(args, this.get('accept'));
}
request.acceptsEncoding = function(encoding) {
- return !!~this.acceptedEncodings.indexOf(encoding);
+ return !!~this.acceptedEncodings.indexOf(encoding);
}
request.acceptsCharset = function(charset) {
- var accepted = this.acceptedCharsets;
+ var accepted = this.acceptedCharsets;
- return accepted.length ? !!~accepted.indexOf(charset) : true;
+ return accepted.length ? !!~accepted.indexOf(charset) : true;
}
request.acceptsLanguage = function(lang) {
- var accepted = this.acceptedLanguages;
+ var accepted = this.acceptedLanguages;
- return accepted.length ? !!~accepted.indexOf(lang) : true;
+ return accepted.length ? !!~accepted.indexOf(lang) : true;
}
// TODO: cache parsed range in _ranges?
request.__defineGetter__('ranges', function() {
- var range = this.get('range');
+ var range = this.get('range');
- // return this._ranges || (this._ranges = parseRanges(range));
- return parseRanges(range);
+ // return this._ranges || (this._ranges = parseRanges(range));
+ return parseRanges(range);
});
request.range = function(size) {
- var range = this.get('range');
+ var range = this.get('range');
- if (range) {
- return parseRange(size, range);
- }
+ if (range) {
+ return parseRange(size, range);
+ }
}
request.__defineGetter__('acceptedEncodings', function() {
- var accept = this.get('accept-encoding');
+ var accept = this.get('accept-encoding');
- return accept ? accept.trim().split(/ *, */) : [];
+ return accept ? accept.trim().split(/ *, */) : [];
});
request.__defineGetter__('accepted', function() {
- var accept = this.get('accept');
+ var accept = this.get('accept');
- return accept ? utils.parseAccept(accept) : [];
+ return accept ? utils.parseAccept(accept) : [];
});
request.__defineGetter__('acceptedLanguages', function() {
- var accept = this.get('accept-language');
+ var accept = this.get('accept-language');
- return accept ? utils.parseParams(accept).map(function(obj) { return obj.value; }) : [];
+ return accept ? utils.parseParams(accept).map(function(obj) { return obj.value; }) : [];
});
request.__defineGetter__('acceptedCharsets', function() {
- var accept = this.get('accept-charset');
+ var accept = this.get('accept-charset');
- return accept ? utils.parseParams(accept).map(function(obj) { return obj.value; }) : [];
+ return accept ? utils.parseParams(accept).map(function(obj) { return obj.value; }) : [];
});
request.param = function(name, defaultValue) {
- var params = this.params || {};
- var data = this.data || {};
- var query = this.query || {};
+ var params = this.params || {};
+ var data = this.data || {};
+ var query = this.query || {};
- if (params[name] != null && params.hasOwnProperty(name)) { return params[name]; }
- if (data[name]) { return data[name]; }
- if (query[name]) { return query[name]; }
+ if (params[name] != null && params.hasOwnProperty(name)) { return params[name]; }
+ if (data[name]) { return data[name]; }
+ if (query[name]) { return query[name]; }
- return defaultValue;
+ return defaultValue;
}
request.is = function(type) {
- var ct = this.get('content-type');
+ var ct = this.get('content-type');
- if (!ct) { return false; }
+ if (!ct) { return false; }
- ct = ct.split(';')[0];
+ ct = ct.split(';')[0];
- if (!~type.indexOf('/')) { type = mime.lookup(type); }
- if (~type.indexOf('*')) {
- type = type.split('/');
- ct = ct.split('/');
+ if (!~type.indexOf('/')) { type = mime.lookup(type); }
+ if (~type.indexOf('*')) {
+ type = type.split('/');
+ ct = ct.split('/');
- if (type[0]==='*' && type[1]===ct[1]) { return true; }
- if (type[1]==='*' && type[0]===ct[0]) { return true; }
+ if (type[0]==='*' && type[1]===ct[1]) { return true; }
+ if (type[1]==='*' && type[0]===ct[0]) { return true; }
- return false;
- }
+ return false;
+ }
- return !!~ct.indexOf(type);
+ return !!~ct.indexOf(type);
}
request.__defineGetter__('protocol', function() {
- var trustProxy = App.get('trustProxy');
+ var trustProxy = App.get('trustProxy');
- if (this.connection.encrypted) { return 'https'; }
- if (!trustProxy) { return 'http'; }
+ if (this.connection.encrypted) { return 'https'; }
+ if (!trustProxy) { return 'http'; }
- var proto = this.get('x-forwarded-proto') || 'http';
+ var proto = this.get('x-forwarded-proto') || 'http';
- return proto.split(/\s*,\s*/)[0];
+ return proto.split(/\s*,\s*/)[0];
});
request.__defineGetter__('secure', function() {
- return this.protocol === 'https';
+ return this.protocol === 'https';
});
request.__defineGetter__('ip', function() {
- return this.ips[0] || this.connection.remoteAddress;
+ return this.ips[0] || this.connection.remoteAddress;
});
request.__defineGetter__('ips', function() {
- var trustProxy = App.get('trustProxy');
- var val = this.get('x-forwarded-for');
+ var trustProxy = App.get('trustProxy');
+ var val = this.get('x-forwarded-for');
- return (trustProxy && val) ? val.split(/ *, */) : [];
+ return (trustProxy && val) ? val.split(/ *, */) : [];
});
request.__defineGetter__('auth', function() {
- var auth = this.get('authorization');
+ var auth = this.get('authorization');
- if (!auth) { return; }
+ if (!auth) { return; }
- var parts = auth.split(' ');
+ var parts = auth.split(' ');
- if (parts[0].toLowerCase() !== 'basic') { return; }
- if (!parts[1]) { return; }
+ if (parts[0].toLowerCase() !== 'basic') { return; }
+ if (!parts[1]) { return; }
- auth = parts[1];
+ auth = parts[1];
- if (!(auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/))) { return; }
+ if (!(auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/))) { return; }
- return { username: auth[1], password: auth[2] };
+ return { username: auth[1], password: auth[2] };
});
request.__defineGetter__('subdomains', function() {
- var offset = App.get('subdomain offset') || 2;
+ var offset = App.get('subdomain offset') || 2;
- return (this.host || '').split('.').reverse().slice(offset);
+ return (this.host || '').split('.').reverse().slice(offset);
});
request.__defineGetter__('host', function() {
- var trustProxy = App.get('trustProxy');
- var host = trustProxy && this.get('x-forwarded-host');
+ var trustProxy = App.get('trustProxy');
+ var host = trustProxy && this.get('x-forwarded-host');
- host = host || this.get('host');
+ host = host || this.get('host');
- return host ? host.split(':')[0] : undefined;
+ return host ? host.split(':')[0] : undefined;
});
request.__defineGetter__('fresh', function() {
- var method = this.method;
- var status = this.response.statusCode;
+ var method = this.method;
+ var status = this.response.statusCode;
- if (method === 'GET' || method === 'HEAD') {
- if ((status >= 200 && status < 300) || status === 304) {
- return fresh(this.headers, this.response._headers);
- }
- }
+ if (method === 'GET' || method === 'HEAD') {
+ if ((status >= 200 && status < 300) || status === 304) {
+ return fresh(this.headers, this.response._headers);
+ }
+ }
- return false;
+ return false;
});
request.__defineGetter__('stale', function() {
- return !this.fresh;
+ return !this.fresh;
});
request.__defineGetter__('xhr', function() {
- var val = this.get('x-requested-with') || '';
+ var val = this.get('x-requested-with') || '';
- return (val.toLowerCase() === 'xmlhttprequest');
+ return (val.toLowerCase() === 'xmlhttprequest');
});
request.__defineGetter__('ajax', function() {
- return this.xhr;
+ return this.xhr;
});
View
546 lib/response.js
@@ -18,346 +18,346 @@ var extname = Path.extname;
var statusCodes = Http.STATUS_CODES;
var response = module.exports = {
- __proto__: Http.ServerResponse.prototype
+ __proto__: Http.ServerResponse.prototype
};
response.__defineGetter__('req', function() {
- return this.request;
+ return this.request;
});
response.status = function(code) {
- this.statusCode = code;
+ this.statusCode = code;
- return this;
+ return this;
}
response.links = function(links) {
- var link = this.get('link') || '';
+ var link = this.get('link') || '';
- if (link) { link += ', '; }
+ if (link) { link += ', '; }
- return this.set('link', link + Object.keys(links).map(function(rel) {
- return '<'+ links[rel] +'>; rel="'+ rel +'"';
- }).join(', '));
+ return this.set('link', link + Object.keys(links).map(function(rel) {
+ return '<'+ links[rel] +'>; rel="'+ rel +'"';
+ }).join(', '));
}
response.contentType =
response.type = function(type) {
- return this.set('Content-Type', ~type.indexOf('/') ? type : mime.lookup(type));
+ return this.set('Content-Type', ~type.indexOf('/') ? type : mime.lookup(type));
}
response.format = function(obj) {
- var request = this.request;
+ var request = this.request;
- var fn = obj.default;
- if (fn) {
- delete obj.default;
- }
+ var fn = obj.default;
+ if (fn) {
+ delete obj.default;
+ }
- var keys = Object.keys(obj);
- var key = request.accepts(keys);
+ var keys = Object.keys(obj);
+ var key = request.accepts(keys);
- this.vary('accept');
+ this.vary('accept');
- if (key) {
- var type = normalizeType(key).value;
- var charset = mime.charsets.lookup(type);
+ if (key) {
+ var type = normalizeType(key).value;
+ var charset = mime.charsets.lookup(type);
- if (charset) { type += '; charset='+ charset; }
+ if (charset) { type += '; charset='+ charset; }
- this.set('Content-Type', type);
+ this.set('Content-Type', type);
- obj[key](request, this);
- } else if (fn) {
- fn();
- } else {
- response.writeHead(406, { 'Content-Type': 'text/plain' });
- response.end('Not Acceptable');
- return;
- // use this.send(error)? or this.send(error.status, error.message);
- var error = new Error('Not Acceptable');
- error.status = 406;
- error.types = normalizeTypes(keys).map(function(o) { return o.value; })
- this.send(error);
- }
+ obj[key](request, this);
+ } else if (fn) {
+ fn();
+ } else {
+ response.writeHead(406, { 'Content-Type': 'text/plain' });
+ response.end('Not Acceptable');
+ return;
+ // use this.send(error)? or this.send(error.status, error.message);
+ var error = new Error('Not Acceptable');
+ error.status = 406;
+ error.types = normalizeTypes(keys).map(function(o) { return o.value; })
+ this.send(error);
+ }
- return this;
+ return this;
}
response.set =
response.header = function(name, value) {
- if (arguments.length === 2) {
- value = Array.isArray(value) ? value.map(String) : String(value);
- this.setHeader(name, value);
- } else {
- for (var key in name) {
- this.set(key, name[key]);
- }
- }
-
- return this;
+ if (arguments.length === 2) {
+ value = Array.isArray(value) ? value.map(String) : String(value);
+ this.setHeader(name, value);
+ } else {
+ for (var key in name) {
+ this.set(key, name[key]);
+ }
+ }
+
+ return this;
}
response.get = function(name) {
- return this.getHeader(name);
+ return this.getHeader(name);
}
response.location = function(url) {
- var request = this.request;
- var path = null;
+ var request = this.request;
+ var path = null;
- var map = { back: request.get('referer') || '/' };
+ var map = { back: request.get('referer') || '/' };
- url = map[url] || url;
+ url = map[url] || url;
- if (!~url.indexOf('://') && url.indexOf('//') !== 0) {
- if (url[0] === '.') {
- path = request.originalUrl.split('?')[0];
- path = path + (path[path.length - 1]==='/' ? '' : '/');
- url = resolve(path, url);
- } else if (url[0] !== '/') {
- // prepend baseUrl?
- // path = App.get('baseUrl');
- // url = path +'/'+ url;
- url = '/'+ url;
- }
- }
+ if (!~url.indexOf('://') && url.indexOf('//') !== 0) {
+ if (url[0] === '.') {
+ path = request.originalUrl.split('?')[0];
+ path = path + (path[path.length - 1]==='/' ? '' : '/');
+ url = resolve(path, url);
+ } else if (url[0] !== '/') {
+ // prepend baseUrl?
+ // path = App.get('baseUrl');
+ // url = path +'/'+ url;
+ url = '/'+ url;
+ }
+ }
- this.set('Location', url);
+ this.set('Location', url);
- return this;
+ return this;
}
response.redirect = function(url) {
- var head = this.request.method === 'HEAD';
- var status = 302;
- var body = null;
-
- if (arguments.length === 2) {
- if (typeof(url) === 'number') {
- status = url;
- url = arguments[1];
- } else {
- status = arguments[1];
- }
- }
-
- this.location(url);
-
- url = this.get('location');
-
- this.format({
- text: function() {
- body = statusCodes[status] +'. Redirecting to '+ encodeURI(url);
- },
-
- html: function() {
- var u = utils.escape(url);
- body = '<p>'+ statusCodes[status] +'. Redirecting to <a href="'+ u +'">'+ u +'</a></p>';
- },
-
- default: function() {
- body = '';
- }
- });
-
- this.statusCode = status;
- this.set('Content-Length', Buffer.byteLength(body));
- this.end(head ? null : body);
+ var head = this.request.method === 'HEAD';
+ var status = 302;
+ var body = null;
+
+ if (arguments.length === 2) {
+ if (typeof(url) === 'number') {
+ status = url;
+ url = arguments[1];
+ } else {
+ status = arguments[1];
+ }
+ }
+
+ this.location(url);
+
+ url = this.get('location');
+
+ this.format({
+ text: function() {
+ body = statusCodes[status] +'. Redirecting to '+ encodeURI(url);
+ },
+
+ html: function() {
+ var u = utils.escape(url);
+ body = '<p>'+ statusCodes[status] +'. Redirecting to <a href="'+ u +'">'+ u +'</a></p>';
+ },
+
+ default: function() {
+ body = '';
+ }
+ });
+
+ this.statusCode = status;
+ this.set('Content-Length', Buffer.byteLength(body));
+ this.end(head ? null : body);
}
response.vary = function(name) {
- var self = this;
+ var self = this;
- if (!name) { return this; }
+ if (!name) { return this; }
- if (Array.isArray(name)) {
- name.forEach(function(name) {
- self.vary(name);
- });
- return;
- }
+ if (Array.isArray(name)) {
+ name.forEach(function(name) {
+ self.vary(name);
+ });
+ return;
+ }
- var vary = this.get('vary');
- if (vary) {
- vary = vary.split(/ *, */);
- !~vary.indexOf(name) && vary.push(name);
+ var vary = this.get('vary');
+ if (vary) {
+ vary = vary.split(/ *, */);
+ !~vary.indexOf(name) && vary.push(name);
- this.set('Vary', vary.join(', '));
+ this.set('Vary', vary.join(', '));
- return this;
- }
+ return this;
+ }
- this.set('Vary', name);
+ this.set('Vary', name);
- return this;
+ return this;
}
response.send = function(status, body) {
- var request = this.request;
- var head = request.method === 'HEAD';
- var len = null;
-
- if (body === undefined) {
- body = status;
- status = null;
- } else {
- this.statusCode = status;
- }
-
- var type = typeof(body);
-
- if (!status && type==='number') {
- this.get('Content-Type') || this.type('txt');
- this.statusCode = body;
- body = statusCodes[body];
- } else if (type === 'string') {
- if (!this.get('Content-Type')) {
- this.charset = this.charset || 'utf-8';
- this.type('html');
- }
- } else if (type==='object' || type==='boolean') {
- if (body == null) {
- body = '';
- } else if (Buffer.isBuffer(body)) {
- this.get('Content-Type') || this.type('bin');
- } else {
- return this.json(body);
- }
- }
-
- if (body !== undefined && !this.get('Content-Length')) {
- this.set('Content-Length', (len = Buffer.isBuffer(body)) ? body.length : Buffer.byteLength(body));
- }
-
- if (App.get('etag') && len && request.method==='GET') {
- if (!this.get('ETag')) {
- this.set('Etag', etag(body));
- }
- }
-
- if (request.fresh) { this.statusCode = 304; }
- if (this.statusCode===204 || this.statusCode===304) {
- this.removeHeader('Content-Type');
- this.removeHeader('Content-Length');
- this.removeHeader('Transfer-Encoding');
-
- body = '';
- }
-
- this.end(head ? null : body);
-
- return this;
+ var request = this.request;
+ var head = request.method === 'HEAD';
+ var len = null;
+
+ if (body === undefined) {
+ body = status;
+ status = null;
+ } else {
+ this.statusCode = status;
+ }
+
+ var type = typeof(body);
+
+ if (!status && type==='number') {
+ this.get('Content-Type') || this.type('txt');
+ this.statusCode = body;
+ body = statusCodes[body];
+ } else if (type === 'string') {
+ if (!this.get('Content-Type')) {
+ this.charset = this.charset || 'utf-8';
+ this.type('html');
+ }
+ } else if (type==='object' || type==='boolean') {
+ if (body == null) {
+ body = '';
+ } else if (Buffer.isBuffer(body)) {
+ this.get('Content-Type') || this.type('bin');
+ } else {
+ return this.json(body);
+ }
+ }
+
+ if (body !== undefined && !this.get('Content-Length')) {
+ this.set('Content-Length', (len = Buffer.isBuffer(body)) ? body.length : Buffer.byteLength(body));
+ }
+
+ if (App.get('etag') && len && request.method==='GET') {
+ if (!this.get('ETag')) {
+ this.set('Etag', etag(body));
+ }
+ }
+
+ if (request.fresh) { this.statusCode = 304; }
+ if (this.statusCode===204 || this.statusCode===304) {
+ this.removeHeader('Content-Type');
+ this.removeHeader('Content-Length');
+ this.removeHeader('Transfer-Encoding');
+
+ body = '';
+ }
+
+ this.end(head ? null : body);
+
+ return this;
}
response.json = function(status, obj) {
- if (obj === undefined) {
- obj = status;
- status = null;
- } else {
- this.statusCode = status;
- }
+ if (obj === undefined) {
+ obj = status;
+ status = null;
+ } else {
+ this.statusCode = status;
+ }
- var replacer = App.get('json replacer');
- var spaces = App.get('json spaces');
- var body = JSON.stringify(obj, replacer, spaces);
+ var replacer = App.get('json replacer');
+ var spaces = App.get('json spaces');
+ var body = JSON.stringify(obj, replacer, spaces);
- this.charset = this.charset || 'utf-8';
- this.get('Content-Type') || this.set('Content-Type', 'application/json');
+ this.charset = this.charset || 'utf-8';
+ this.get('Content-Type') || this.set('Content-Type', 'application/json');
- return this.send(body);
+ return this.send(body);
}
response.jsonp = function(status, obj) {
- if (obj === undefined) {
- obj = status;
- status = null;
- } else {
- this.statusCode = status;
- }
-
- var replacer = App.get('json replacer');
- var spaces = App.get('json spaces');
- var body = JSON.stringify(obj, replacer, spaces).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
- var callback = App.get('jsonp callback');
+ if (obj === undefined) {
+ obj = status;
+ status = null;
+ } else {
+ this.statusCode = status;
+ }
+
+ var replacer = App.get('json replacer');
+ var spaces = App.get('json spaces');
+ var body = JSON.stringify(obj, replacer, spaces).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
+ var callback = App.get('jsonp callback');
this.charset = this.charset || 'utf-8';
this.set('Content-Type', 'application/json');
- if (callback) {
- !Array.isArray(callback) && (callback = [callback]);
- for (var i=0; i<callback.length; i++) {
- var cb = this.request.query[callback[i]];
+ if (callback) {
+ !Array.isArray(callback) && (callback = [callback]);
+ for (var i=0; i<callback.length; i++) {
+ var cb = this.request.query[callback[i]];
- if (cb) {
- if (Array.isArray(cb)) { cb = cb[0]; }
+ if (cb) {
+ if (Array.isArray(cb)) { cb = cb[0]; }
- this.set('Content-Type', 'text/javascript');
+ this.set('Content-Type', 'text/javascript');
- cb = cb.replace(/[^\[\]\w$.]/g, '');
- body = 'typeof '+ cb +' === \'function\' && '+ cb +'('+ body +');';
+ cb = cb.replace(/[^\[\]\w$.]/g, '');
+ body = 'typeof '+ cb +' === \'function\' && '+ cb +'('+ body +');';
- break;
- }
- }
- }
+ break;
+ }
+ }
+ }
- return this.send(body);
+ return this.send(body);
}
response.attachment = function(filename) {
- if (filename) { this.type(extname(filename)); }
+ if (filename) { this.type(extname(filename)); }
- this.set('Content-Disposition', filename ? 'attachment; filename="'+ basename(filename) +'"' : 'attachment');
+ this.set('Content-Disposition', filename ? 'attachment; filename="'+ basename(filename) +'"' : 'attachment');
- return this;
+ return this;
}
response.sendFile = function(status, path, headers, callback) {
- if (typeof(status) === 'string') {
- callback = headers; headers = path; path = status; status = 200;
- }
+ if (typeof(status) === 'string') {
+ callback = headers; headers = path; path = status; status = 200;
+ }
- if (typeof(headers) === 'function') {
- callback = headers; headers = null;
- }
+ if (typeof(headers) === 'function') {
+ callback = headers; headers = null;
+ }
- var promise = fileServer.serveFile(path, status, headers || {}, this.request, this);
+ var promise = fileServer.serveFile(path, status, headers || {}, this.request, this);
- promise.on('error', function(error) {
- callback && callback(error);
- });
+ promise.on('error', function(error) {
+ callback && callback(error);
+ });
- promise.on('success', function(result) {
- callback && callback(null, result);
- });
+ promise.on('success', function(result) {
+ callback && callback(null, result);
+ });
- return this;
+ return this;
}
response.download = function(path, filename, callback) {
- if (typeof(filename) === 'function') {
- callback = filename;
- filename = null;
- }
+ if (typeof(filename) === 'function') {
+ callback = filename;
+ filename = null;
+ }
- filename = filename || path;
+ filename = filename || path;
- this.set('Content-Disposition', 'attachment; filename="'+ basename(filename) +'"');
+ this.set('Content-Disposition', 'attachment; filename="'+ basename(filename) +'"');
- return this.sendFile(path, callback);
+ return this.sendFile(path, callback);
}
response.render = function(path, data) {
- var self = this;
+ var self = this;
- App.render(path, data, function(error, content) {
- if (error) {
- return self.send(500);
- }
+ App.render(path, data, function(error, content) {
+ if (error) {
+ return self.send(500);
+ }
- self.send(content);
- });
+ self.send(content);
+ });
}
@@ -367,51 +367,51 @@ var writeHead = response.writeHead;
var _renderHeaders = response._renderHeaders;
response.__defineGetter__('headerSent', function() {
- return this.headersSent;
+ return this.headersSent;
});
response.setHeader = function(field, value) {
- var key = field.toLowerCase();
- var prev;
-
- if (this._headers && key==='set-cookie') {
- if (prev = this.getHeader(field)) {
- if (Array.isArray(prev)) {
- value = prev.concat(value);
- } else if (Array.isArray(value)) {
- value = value.concat(prev);
- } else {
- value = [prev, value];
- }
- }
- } else if (key==='content-type' && this.charset) {
- value += '; charset='+ this.charset;
- }
-
- return setHeader.call(this, field, value);
+ var key = field.toLowerCase();
+ var prev;
+
+ if (this._headers && key==='set-cookie') {
+ if (prev = this.getHeader(field)) {
+ if (Array.isArray(prev)) {
+ value = prev.concat(value);
+ } else if (Array.isArray(value)) {
+ value = value.concat(prev);
+ } else {
+ value = [prev, value];
+ }
+ }
+ } else if (key==='content-type' && this.charset) {
+ value += '; charset='+ this.charset;
+ }
+
+ return setHeader.call(this, field, value);
}
response._renderHeaders = function() {
- if (!this._emittedHeader) {
- this.emit('header');
- }
+ if (!this._emittedHeader) {
+ this.emit('header');
+ }
- this._emittedHeader = true;
+ this._emittedHeader = true;
- return _renderHeaders.call(this);
+ return _renderHeaders.call(this);
}
response.writeHead = function(statusCode, reasonPhrase, headers) {
- if (typeof(reasonPhrase) === 'object') { headers = reasonPhrase; }
- if (typeof(headers) === 'object') {
- Object.keys(headers).forEach(function(key) {
- this.setHeader(key, headers[key]);
- }, this);
- }
+ if (typeof(reasonPhrase) === 'object') { headers = reasonPhrase; }
+ if (typeof(headers) === 'object') {
+ Object.keys(headers).forEach(function(key) {
+ this.setHeader(key, headers[key]);
+ }, this);
+ }
- if (!this._emittedHeader) { this.emit('header'); }
+ if (!this._emittedHeader) { this.emit('header'); }
- this._emittedHeader = true;
+ this._emittedHeader = true;
- return writeHead.call(this, statusCode, reasonPhrase);
+ return writeHead.call(this, statusCode, reasonPhrase);
}
View
156 lib/router.js
@@ -14,11 +14,11 @@ router.prepare = function(rules, module) {
self.routes[module] = {};
for (var i=0; i<rules.length; i++) {
- var rule = rules[i][0];
- var path = rules[i][1];
- var method = '*';
+ var rule = rules[i][0];
+ var path = rules[i][1];
+ var method = '*';
- var match = null;
+ var match = null;
if (rule !=='*' && (match = rule.match(new RegExp('^((?:(?:'+ verbs +')\\|?)*)*\\s*(.*)$', 'i')))) {
method = (!match[1] || match[1]==='*') ? '*' : match[1];
@@ -43,21 +43,21 @@ router.prepare = function(rules, module) {
}
router.normalize = function(rule, keys) {
- var index = 0;
+ var index = 0;
- if (rule instanceof RegExp) {
- var k = rule.source.match(/\(.*?\)/g)
+ if (rule instanceof RegExp) {
+ var k = rule.source.match(/\(.*?\)/g)
- for (; index<k.length ;) {
- keys.push({ name: ++index });
- }
+ for (; index<k.length ;) {
+ keys.push({ name: ++index });
+ }
- return rule;
- }
+ return rule;
+ }
- // rule = sanitize(rule).trim('\\s\/')
- rule = rule
- .replace(/\/\(/g, '(?:/')
+ // rule = sanitize(rule).trim('\\s\/')
+ rule = rule
+ .replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star) {
keys.push({ name: key || ++index, optional: !!optional });
slash = slash || '';
@@ -76,94 +76,94 @@ router.normalize = function(rule, keys) {
}
App._modules.forEach(function(module) {
- router.prepare(App.get(module +':routing routes') || [], module);
+ router.prepare(App.get(module +':routing routes') || [], module);
});
// TODO: try to deal with optional params
router.route = function(uri, method, module, useRoutes) {
- var self = this;
+ var self = this;
- module = module || 'app';
- method = method || 'GET';
- useRoutes===undefined && (useRoutes = true);
+ module = module || 'app';
+ method = method || 'GET';
+ useRoutes===undefined && (useRoutes = true);
- var routed = uri;
+ var routed = uri;
- var conf = App.get((module) +':routing') || {};
- conf.route || (conf.route = {});
+ var conf = App.get((module) +':routing') || {};
+ conf.route || (conf.route = {});
- var route = {
- module: module,
- directory: conf.route.directory || '',
- controller: conf.route.controller || (module==='app' ? 'home' : module),
- action: conf.route.action || 'index',
- arguments: conf.route.arguments || [],
- params: conf.route.params || {},
- routed: routed
- }
+ var route = {
+ module: module,
+ directory: conf.route.directory || '',
+ controller: conf.route.controller || (module==='app' ? 'home' : module),
+ action: conf.route.action || 'index',
+ arguments: conf.route.arguments || [],
+ params: conf.route.params || {},
+ routed: routed
+ }
- var found = false;
- var mod = null;
+ var found = false;
+ var mod = null;
- if (useRoutes) {
- [method.toLowerCase(), '*'].forEach(function(method) {
- var rules = self.routes[module][method];
+ if (useRoutes) {
+ [method.toLowerCase(), '*'].forEach(function(method) {
+ var rules = self.routes[module][method];
- if (!found && rules) {
- for (var i=0; i<rules.length; i++) {
- var rule = rules[i];
- var match = null;
+ if (!found && rules) {
+ for (var i=0; i<rules.length; i++) {
+ var rule = rules[i];
+ var match = null;
- if (match = uri.match(rule.regexp)) {
- found = true;
- match = match.slice(1);
- routed = rule.path;
+ if (match = uri.match(rule.regexp)) {
+ found = true;
+ match = match.slice(1);
+ routed = rule.path;
- for (var j=0; j<match.length; j++) {
- var key = rule.keys[j];
- var name = key ? key.name : j+1;
+ for (var j=0; j<match.length; j++) {
+ var key = rule.keys[j];
+ var name = key ? key.name : j+1;
- route.params[name] = match[j];
- routed = routed.replace(':'+ name, match[j] || '');
- }
+ route.params[name] = match[j];
+ routed = routed.replace(':'+ name, match[j] || '');
+ }
routed = routed.replace(/^\/|\/$/, '');
- if (route.module==='app' && (mod = routed[0]==='#')) {
- routed = routed.substr(1);
- }
+ if (route.module==='app' && (mod = routed[0]==='#')) {
+ routed = routed.substr(1);
+ }
- // remove optional params
- // routed = routed.replace(/\/?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/, '');
+ // remove optional params
+ // routed = routed.replace(/\/?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/, '');
- // TODO: find a better way to set controller directory
- routed = routed.replace(/\[(.*)\](\/)?/, function(_, dir) {
- route.directory = sanitize(dir.toLowerCase()).trim('\\s\/') + '/';
+ // TODO: find a better way to set controller directory
+ routed = routed.replace(/\[(.*)\](\/)?/, function(_, dir) {
+ route.directory = sanitize(dir.toLowerCase()).trim('\\s\/') + '/';
- // TODO: keep directory in routed path for module re-routing?
- // return route.directory;
- return '';
- });
+ // TODO: keep directory in routed path for module re-routing?
+ // return route.directory;
+ return '';
+ });
route.routed = routed;
- break;
- }
- }
- }
- });
- }
+ break;
+ }
+ }
+ }
+ });
+ }
- var segments = routed.indexOf('/') !== -1 ? routed.split('/') : [routed];
+ var segments = routed.indexOf('/') !== -1 ? routed.split('/') : [routed];
- if (segments.length && mod) {
- route.module = segments.shift().toLowerCase();
- route.routed = route.routed.replace(new RegExp('^'+ route.module +'[\/]?', 'i'), '');
- }
+ if (segments.length && mod) {
+ route.module = segments.shift().toLowerCase();
+ route.routed = route.routed.replace(new RegExp('^'+ route.module +'[\/]?', 'i'), '');
+ }
- segments.length && (route.controller = segments.shift().toLowerCase() || (module==='app' ? 'home' : module));
- segments.length && (route.action = segments.shift().toLowerCase());
- segments.length && (route.arguments = segments);
+ segments.length && (route.controller = segments.shift().toLowerCase() || (module==='app' ? 'home' : module));
+ segments.length && (route.action = segments.shift().toLowerCase());
+ segments.length && (route.arguments = segments);
- return route;
+ return route;
}
View
10 lib/session/memory.js
@@ -1,16 +1,16 @@
var Memory = module.exports = function(conf) {
- this.conf = conf;
- this.store = App.store(conf.store.name);
+ this.conf = conf;
+ this.store = App.store(conf.store.name);
}
Memory.prototype.read = function(id, callback) {
- callback(null, this.store.get(this.conf.store.prefix +':'+ id) || {});
+ callback(null, this.store.get(this.conf.store.prefix +':'+ id) || {});
}
Memory.prototype.write = Memory.prototype.save = function(id, data, callback) {
- this.store.set(this.conf.store.prefix +':'+ id, data);
+ this.store.set(this.conf.store.prefix +':'+ id, data);
- callback(null, data);
+ callback(null, data);
}
Memory.prototype.delete = function(id, callback) {
View
18 lib/session/redis.js
@@ -1,20 +1,20 @@
var Redis = module.exports = function(conf) {
- this.conf = conf;
- this.store = App.store(conf.store.name);
+ this.conf = conf;
+ this.store = App.store(conf.store.name);
}
Redis.prototype.read = function(id, callback) {
- this.store.get(this.conf.store.prefix +':'+ id, function(error, data) {
- if (error) {
- return callback(error);
- }
+ this.store.get(this.conf.store.prefix +':'+ id, function(error, data) {
+ if (error) {
+ return callback(error);
+ }
- callback(null, data ? JSON.parse(data) : {});
- });
+ callback(null, data ? JSON.parse(data) : {});
+ });
}
Redis.prototype.write = Redis.prototype.save = function(id, data, callback) {
- this.store.setex(this.conf.store.prefix +':'+ id, this.conf.expires, JSON.stringify(data), callback);
+ this.store.setex(this.conf.store.prefix +':'+ id, this.conf.expires, JSON.stringify(data), callback);
}
Redis.prototype.delete = function(id, callback) {
View
49 modules.json
@@ -1,52 +1,3 @@
{
- "auth": {
- "description": "Basic authorization and authentication module with roles and rights",
-
- "author": {
- "name": "Shogun147",
- "email": "Shogun147@gmail.com",
- "url": "https://github.com/Shogun147"
- },
-
- "github": {
- "username": "Shogun147",
- "repository": "Katana-auth"
- },
-
- "tags": ["v0.1.0"]
- },
-
- "methodOverride": {
- "description": "Faux HTTP method support",
- "author": {
- "name": "Shogun147",
- "email": "Shogun147@gmail.com",
- "url": "https://github.com/Shogun147"
- },
-
- "github": {
- "username": "Shogun147",
- "repository": "Katana-methodOverride"
- },
-
- "tags": ["v0.1.0"]
- },
-
- "csrf": {
- "description": "CSRF protection",
-
- "author": {
- "name": "Shogun147",
- "email": "Shogun147@gmail.com",
- "url": "https://github.com/Shogun147"
- },
-
- "github": {
- "username": "Shogun147",
- "repository": "Katana-csrf"
- },
-
- "tags": ["v0.1.0"]
- }
}
View
4 template/app.js
@@ -4,9 +4,7 @@ require('katana');
process.title = 'Node: '+ App.info.name;
App.use(function(request, response, next) {
- response.on('header', function() {
- response.setHeader('X-Powered-By', 'Katana v'+ App.version);
- });
+ response.setHeader('X-Powered-By', 'Katana v'+ App.version);
next();
});
View
11 template/app/config/development/app.js
@@ -1,7 +1,4 @@
-var Path = require('path');
-var Fs = require('fs');
-
-var root = process.cwd() + Path.sep;
+var Fs = require('fs');
module.exports = {
url: 'localhost',
@@ -15,8 +12,8 @@ module.exports = {
// https: {
// host: '127.0.0.1',
// port: 1443,
- // key: Fs.readFileSync(root + 'server.key'),
- // cert: Fs.readFileSync(root + 'server.crt'),
+ // key: Fs.readFileSync(App.root + 'server.key'),
+ // cert: Fs.readFileSync(App.root + 'server.crt'),
// ca: null
// },
@@ -84,7 +81,7 @@ module.exports = {
maxFields: 1000,
maxFieldsSize: 2 * 1024 * 1024,
- uploadDir: Path.join(root, 'temp', 'files'),
+ uploadDir: Path.join(App.root, 'temp', 'files'),
keepExtensions: false,
encoding: 'utf-8',

0 comments on commit 4a6b7af

Please sign in to comment.
Something went wrong with that request. Please try again.