express.core.js
This file
Path
lib/express.core.js
725 lines · 18.9 KiB · JavaScript
Last changed by
fixed overriding of path by mock requestcsausdevbefore adoption9fb91c6
History of this fileTake it
12// Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)3process.mixin(GLOBAL, require("sys"));4 5(function(){6 var http = require("http");7 8 Express = { 9 version : '0.0.1',10 utilities : {},11 modules : [],12 routes : [],13 STATUS_CODES : {14 100 : 'Continue',15 101 : 'Switching Protocols',16 200 : 'OK',17 201 : 'Created',18 202 : 'Accepted',19 203 : 'Non-Authoritative Information',20 204 : 'No Content',21 205 : 'Reset Content',22 206 : 'Partial Content',23 300 : 'Multiple Choices',24 301 : 'Moved Permanently',25 302 : 'Moved Temporarily',26 303 : 'See Other',27 304 : 'Not Modified',28 305 : 'Use Proxy',29 400 : 'Bad Request',30 401 : 'Unauthorized',31 402 : 'Payment Required',32 403 : 'Forbidden',33 404 : 'Not Found',34 405 : 'Method Not Allowed',35 406 : 'Not Acceptable',36 407 : 'Proxy Authentication Required',37 408 : 'Request Time-out',38 409 : 'Conflict',39 410 : 'Gone',40 411 : 'Length Required',41 412 : 'Precondition Failed',42 413 : 'Request Entity Too Large',43 414 : 'Request-URI Too Large',44 415 : 'Unsupported Media Type',45 500 : 'Internal Server Error',46 501 : 'Not Implemented',47 502 : 'Bad Gateway',48 503 : 'Service Unavailable',49 504 : 'Gateway Time-out',50 505 : 'HTTP Version not supported'51 },52 53 // --- Halt54 55 Halt : function(){56 this.toString = function() {57 return 'Express.Halt'58 }59 },60 61 // --- Response62 63 response : {64 headers : {},65 cookie : {}66 },67 68 // --- Settings69 70 settings : {71 basepath : '/',72 defaultRoute : {73 callback : function() {74 Express.respond('Page or file cannot be found', 'Not Found')75 }76 }77 },78 79 // --- Modules80 81 RedirectHelpers : {82 init : function() {83 Express.home = Express.settings.basepath84 },85 86 onRequest : {87 'set back to referrer' : function() {88 Express.back = 89 Express.requestHeader('Referer') ||90 Express.requestHeader('Referrer')91 }92 }93 },94 95 ContentLength : {96 onResponse : {97 'set content length' : function() {98 Express.header('Content-Length', (Express.response.body || '').length)99 }100 }101 },102 103 DefaultContentType : {104 onRequest : {105 'set response content type to text/html' : function() {106 Express.header('Content-Type', 'text/html')107 }108 }109 },110 111 BodyDecoder : {112 onRequest : {113 'parse urlencoded bodies' : function() {114 switch (Express.requestHeader('Content-Type')) {115 case 'application/x-www-form-urlencoded':116 Express.request.uri.params = Express.parseParams(unescape(Express.request.body))117 break118 119 case 'application/json':120 Express.request.uri.params = Express.jsonDecode(Express.request.body)121 break122 }123 }124 }125 },126 127 MethodOverride : {128 onRequest : {129 'set HTTP method to _method when present' : function() {130 if (method = Express.param('_method'))131 Express.request.method = method.toUpperCase()132 }133 }134 },135 136 Logger : {137 onRequest : {138 'output log data' : function(){139 puts('"' + Express.request.method + ' ' + Express.request.uri.path +140 ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)141 }142 }143 },144 145 /**146 * Invoke hook _name_ with _args_, returning147 * an array of return values.148 *149 * @param {string} name150 * @param {...} args151 * @return {array}152 * @api public153 */154 155 hook : function(name, args) {156 var results = []157 for (var i = 0, len = this.modules.length; i < len; ++i)158 for (var key in this.modules[i][name])159 results.push(this.modules[i][name][key].apply(this.modules[i], this.argsArray(arguments, 1))) 160 return results161 },162 163 /**164 * Invoke hook _name_ with _immutable_ and _args_, returning165 * the _immutable_ variable once modified by each hook implementation.166 * When implementing these hooks, the function must return a value.167 *168 * @param {string} name169 * @param {mixed} immutable170 * @param {...} args171 * @return {mixed}172 * @api public173 */174 175 hookImmutable : function(name, immutable, args) {176 for (var i = 0, len = this.modules.length; i < len; ++i)177 for (var key in this.modules[i][name])178 immutable = this.modules[i][name][key].call(this.modules[i], immutable)179 return immutable180 },181 182 /**183 * Add _module_.184 *185 * @param {hash} module186 * @param {...} args187 * @api public188 */189 190 addModule : function(module, args) {191 Express.settings[module.name] = {}192193 if ('init' in module) 194 module.init.apply(module, Express.argsArray(arguments, 1))195196 if ('settings' in module) {197 if (!module.name) throw 'module name is required when using .settings'198 for (var name in module.settings)199 Express.settings[module.name][name] = module.settings[name]200 }201 202 if ('utilities' in module)203 for (var name in module.utilities)204 Express.utilities[name] = module.utilities[name]205 206 Express.modules.push(module)207 },208 209 /**210 * Start Express; binding to _host_ / _port_.211 *212 * @param {int} port213 * @param {string} host214 * @api public215 */216 217 start : function(port, host) {218 this.server.listen(port || 3000, host, this.server.callback)219 },220 221 server : {222 223 /**224 * Listen to _host_ / _port_ with _callback_.225 *226 * @param {int} port227 * @param {string} host228 * @param {function} callback229 * @api private230 */231 232 listen : function(port, host, callback) {233 http.createServer(callback).listen(port, host)234 puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')235 },236 237 /**238 * Request callback.239 *240 * @param {object} request241 * @param {object} response242 * @api private243 */244 245 callback : function(request, response){246 request.body = request.body || ''247 request.setBodyEncoding('utf8')248 request.addListener('body', function(chunk) { request.body += chunk })249 request.addListener('complete', function(){250 Express.home = Express.settings.basepath251 Express.response.body = null252 Express.response.status = 200253 Express.request = request254 request.headers = Express.arrayToHash(request.headers)255 request.uri.params = Express.parseNestedParams(request.uri.params)256 request.uri.path = Express.normalizePath(request.uri.path)257 Express.hook('onRequest')258 try { Express.response.body = Express.callRouteFor(request) }259 catch (e) { Express.fail(e) }260 Express.hook('onResponse')261 response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))262 response.sendBody(Express.response.body || '')263 response.finish()264 })265 }266 },267 268 /**269 * Fail Express with exception _e_.270 *271 * @param {object} e272 * @api private273 */274275 fail : function(e) {276 this.hook('onFailure', e)277 if (e.constructor == Express.Halt) return278 this.header('Content-Type', 'text/plain')279 this.response.body = e.message ? e.name + ': ' + e.message : e.toString()280 this.response.status = 500281 },282 283 /**284 * Return an associative array generated285 * from the key / value pairs in _hash_.286 *287 * @param {hash} hash288 * @return {array}289 * @api public290 */291 292 hashToArray : function(hash) {293 var array = []294 for (var key in hash)295 array.push([key, hash[key]])296 return array297 },298 299 /**300 * Return hash generated from an301 * associative array.302 *303 * @param {array} array304 * @return {hash}305 * @api public306 */307 308 arrayToHash : function(array) {309 var hash = {}310 for (var i = 0, len = array.length; i < len; ++i)311 hash[array[i][0].toLowerCase()] = array[i][1]312 return hash313 },314 315 /**316 * JSON encode _object_317 *318 * @param {mixed} object319 * @return {string}320 * @api public321 */322 323 jsonEncode : function(object) {324 return JSON.stringify(object)325 },326 327 /**328 * JSON decode _string_.329 *330 * @param {string} string331 * @return {mixed}332 * @api public333 */334 335 jsonDecode : function(string) {336 return JSON.parse(string)337 },338 339 /**340 * Redirect to _uri_.341 *342 * @param {string} uri343 * @api public344 */345 346 redirect : function(uri) {347 this.header('Location', uri)348 this.respond("Page or file has moved to `" + uri + "'", 'Moved Temporarily')349 },350 351 /**352 * Set response status to _value_. Where value may be353 * a case-insensitive string such as 'Not Found', 'forbidden',354 * or a numeric HTTP response status code.355 *356 * @param {int, string} value357 * @return {int}358 * @api public359 */360 361 status : function(value) {362 if (value == undefined) return363 if (typeof value == 'number') return this.response.status = value364 for (var code in this.STATUS_CODES)365 if (this.STATUS_CODES[code].toLowerCase() == value.toLowerCase())366 return this.response.status = parseInt(code)367 },368369 /**370 * Return path segment _n_.371 *372 * @param {int} n373 * @return {string}374 * @api public375 */376 377 arg : function(n) {378 return this.request.uri.path.split('/')[n]379 },380 381 /**382 * Set response _status_ and _body_.383 *384 * @param {string} body385 * @param {string, int} status386 * @api public387 */388 389 respond : function(body, status) {390 this.response.body = body391 this.status(status)392 throw new Express.Halt()393 },394 395 /**396 * Get or set response _name_ header.397 *398 * @param {string} name399 * @param {string} value400 * @return {string}401 * @api public402 */403 404 header : function(name, value) {405 return value ? 406 this.response.headers[name.toLowerCase()] = value :407 this.response.headers[name.toLowerCase()]408 },409 410 /**411 * Get request header _name_ optionally providing _default_412 * when _name_ is not present.413 *414 * @param {string} name415 * @param {string} default416 * @return {string}417 * @api public418 */419 420 requestHeader : function(name, defaultValue) {421 return this.request.headers[name.toLowerCase()] || defaultValue422 },423 424 /**425 * Return param _key_'s value or _defaultValue_ when426 * the param has not been set.427 *428 * @param {string} key429 * @param {mixed} defaultValue430 * @return {mixed}431 * @api public432 */433 434 param : function(key, defaultValue) {435 return this.request.uri.params[key] || defaultValue436 },437 438 /**439 * Parse params _string_ into a nested hash.440 *441 * @param {string} string442 * @return {hash}443 * @api public444 */445 446 parseParams : function(string) {447 var params = {}, pairs = string.split('&'), pair448 for (var i = 0, len = pairs.length; i < len; ++i) {449 pair = pairs[i].split('=')450 params[pair[0]] = pair[1]451 }452 return this.parseNestedParams(params)453 },454 455 /**456 * Parse _params_, splitting { user[info][name] : 'tj' } into457 * { user : { info : { name : 'tj' }}}458 *459 * @param {hash} params460 * @return {hash}461 * @api public462 */463 464 parseNestedParams : function(params) {465 for (var key in params)466 if (parts = key.split('['))467 if (parts.length > 1)468 for (var i = 0, prop = params, len = parts.length; i < len; ++i) {469 var name = parts[i].replace(']', '')470 if (i == len - 1) {471 prop[name] = params[key]472 prop = params, delete params[key]473 }474 else {475 prop = prop[name] = prop[name] || {}476 }477 }478 479 return params480 },481 482 /**483 * Parse _cookie_ string into an object (hash).484 *485 * @param {string} cookie486 * @return {hash}487 * @api public488 */489 490 parseCookie : function(cookie) {491 var hash = {}492 if (!cookie) return hash493 var attrs = cookie.split(/\s*;\s*/)494 for (var i = 0; i < attrs.length; ++i)495 hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])496 return hash497 },498 499 /**500 * Normalize a path. Strips trailing / leading whitespace501 * and slashes ('/').502 *503 * @param {string} path504 * @return {string}505 * @api public506 */507 508 normalizePath : function(path) {509 if (typeof path != 'string') return path510 return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')511 },512 513 /**514 * Normalize _path_. When a RegExp it is simply returned,515 * otherwise a string is converted to a regular expression516 * surrounded by ^$. So /user/:id/edit would become:517 *518 * \^/user/(.*?)\/edit\$/519 *520 * Each param key (:id) will be captured and placed in the521 * params array, so param('id') would give the string captured.522 *523 * @param {string} path524 * @return {regexp}525 * @api public526 */527 528 pathToRegexp : function(path) {529 Express.regexpKeys = []530 if (path.constructor == RegExp) return path531 path = path.replace(/:(\w+)/g, function(_, key){532 Express.regexpKeys.push(key)533 return '(.*?)'534 })535 return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')536 },537 538 /**539 * Escape RegExp _chars_ in _string_. Where _chars_ 540 * defaults to regular expression special characters.541 *542 * _chars_ should be a space delimited list of characters,543 * for example '[ ] ( )'.544 *545 * @param {string} string546 * @param {string} chars547 * @return {Type}548 * @api public549 */550 551 escapeRegexp : function(string, chars) {552 var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')553 return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')554 },555 556 /**557 * Return the contents of a function body.558 *559 * @param {function} body560 * @return {string}561 * @api public562 */563 564 contentsOf : function(body) {565 if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"566 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]567 },568 569 /**570 * Eval _string_ in context of Express.571 *572 * @param {string} string573 * @return {mixed}574 * @api public575 */576 577 eval : function(string) {578 return eval('with (Express){ with (Express.utilities){ ' + string + '}}')579 },580 581 /**582 * Escape special characters in _html_.583 *584 * @param {string} html585 * @return {string}586 * @api public587 */588 589 escape : function(html) {590 return html.591 replace(/&/g, '&').592 replace(/"/g, '"').593 replace(/</g, '<').594 replace(/>/g, '>')595 },596 597 /**598 * Convert native arguments object into an599 * array with optional _offset_.600 *601 * @param {arguments} args602 * @param {int} offset603 * @return {array}604 * @api public605 */606 607 argsArray : function(args, offset) {608 return Array.prototype.slice.call(args, offset)609 },610 611 /**612 * Check if _route_ matches provides the proper613 * encoding types listed in _request_'s Accept header.614 *615 * @param {hash} route616 * @param {hash} request617 * @return {bool}618 * @api private619 */620 621 routeProvides : function(route, request) {622 if (!route.options.provides) return true623 if (route.options.provides.constructor != Array) 624 route.options.provides = [route.options.provides]625 for (var i = 0, len = route.options.provides.length; i < len; ++i)626 if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))627 return true628 return false629 },630 631 /**632 * Attept to match and call a route for 633 * the given _request_, returning the data634 * returned by the route callback.635 *636 * @param {object} request637 * @return {mixed}638 * @api private639 */640 641 callRouteFor : function(request) {642 var route = this.findRouteFor(request) || this.settings.defaultRoute643 if (route.keys)644 for (var i = 0, len = route.keys.length; i < len; ++i) 645 this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null646 var body = this.eval(Express.contentsOf(route.callback))647 if (typeof body != 'string') 648 throw "route `" + route.method.toUpperCase() + ' ' + route.path + "' must return a string"649 return body650 },651 652 /**653 * Attemp to find and return a route matching _request_.654 *655 * @param {object} request656 * @return {object}657 * @api private658 */659 660 findRouteFor : function(request) {661 for (var i = 0, len = this.routes.length; i < len; ++i)662 if (this.routeMatches(this.routes[i], request))663 return this.routes[i]664 },665 666 /**667 * Check if _route_ matches _request_668 *669 * @param {object} route670 * @param {object} request671 * @return {bool}672 * @api private673 */674 675 routeMatches : function(route, request) {676 if (request.method.toLowerCase() != route.method) return false677 switch (route.path.constructor) {678 case String: return route.path == request.uri.path679 case RegExp: return !! (Express.captures = request.uri.path.match(route.path))680 }681 },682 683 /**684 * Return a routing function for _method_.685 *686 * @param {string} method687 * @return {function}688 * @api private689 */690 691 routeFunctionFor : function(method) {692 return function(path, options, callback) {693 if (options.constructor == Function) callback = options, options = {}694 path = Express.pathToRegexp(Express.normalizePath(path))695 var route = {696 keys : Express.regexpKeys,697 path : path,698 method : method,699 options : options,700 callback : callback701 }702 Express.routes.push(route)703 Express.hook('onRouteAdded', route)704 }705 }706 }707 708 // --- Expose709 710 get = Express.routeFunctionFor('get')711 post = Express.routeFunctionFor('post')712 del = Express.routeFunctionFor('delete')713 put = Express.routeFunctionFor('put')714 use = Express.addModule715716 // --- Core Modules717 718 use(Express.BodyDecoder)719 use(Express.MethodOverride)720 use(Express.ContentLength)721 use(Express.DefaultContentType)722 use(Express.RedirectHelpers)723 724})()725