express.core.js
This file
Path
lib/express.core.js
695 lines · 17.9 KiB · JavaScript
Last changed by
Reordered onRouteAddedvisionmediabefore adoptione248d77
History of this fileTake it
12// Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){5 Express = { 6 version : '0.0.1',7 utilities : {},8 modules : [],9 routes : [],10 11 // --- Halt12 13 Halt : function(){14 this.toString = function() {15 return 'Express.Halt'16 }17 },18 19 // --- Response20 21 response : {22 headers : {},23 cookie : {}24 },25 26 // --- Settings27 28 settings : {29 basepath : '/',30 defaultRoute : {31 callback : function() {32 Express.respond('Page or file cannot be found', 'Not Found')33 }34 }35 },36 37 // --- Modules38 39 RedirectHelpers : {40 init : function() {41 Express.home = Express.settings.basepath42 }43 },44 45 ContentLength : {46 onResponse : {47 'set content length' : function() {48 Express.header('Content-Length', (Express.response.body || '').length)49 }50 }51 },52 53 DefaultContentType : {54 onRequest : {55 'set response content type to text/html' : function() {56 Express.header('Content-Type', 'text/html')57 }58 }59 },60 61 BodyDecoder : {62 onRequest : {63 'parse urlencoded bodies' : function() {64 switch (Express.requestHeader('Content-Type')) {65 case 'application/x-www-form-urlencoded':66 Express.request.uri.params = Express.parseParams(unescape(Express.request.body))67 break68 69 case 'application/json':70 Express.request.uri.params = Express.jsonDecode(Express.request.body)71 break72 }73 }74 }75 },76 77 MethodOverride : {78 onRequest : {79 'set HTTP method to _method when present' : function() {80 if (method = Express.param('_method'))81 Express.request.method = method.toUpperCase()82 }83 }84 },85 86 Logger : {87 onRequest : {88 'output log data' : function(){89 puts('"' + Express.request.method + ' ' + Express.request.uri.path +90 ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)91 }92 }93 },94 95 /**96 * Invoke hook _name_ with _args_, returning97 * an array of return values.98 *99 * @param {string} name100 * @param {...} args101 * @return {array}102 * @api public103 */104 105 hook : function(name, args) {106 var results = []107 for (i = 0, len = this.modules.length; i < len; ++i)108 for (var key in this.modules[i][name])109 if (this.modules[i][name].hasOwnProperty(key))110 results.push(this.modules[i][name][key].apply(this.modules[i], this.argsArray(arguments, 1))) 111 return results112 },113 114 /**115 * Invoke hook _name_ with _immutable_ and _args_, returning116 * the _immutable_ variable once modified by each hook implementation.117 * When implementing these hooks, the function must return a value.118 *119 * @param {string} name120 * @param {mixed} immutable121 * @param {...} args122 * @return {mixed}123 * @api public124 */125 126 hookImmutable : function(name, immutable, args) {127 for (i = 0, len = this.modules.length; i < len; ++i)128 for (var key in this.modules[i][name])129 if (this.modules[i][name].hasOwnProperty(key))130 immutable = this.modules[i][name][key].call(this.modules[i], immutable)131 return immutable132 },133 134 /**135 * Add _module_.136 *137 * @param {hash} module138 * @param {...} args139 * @api public140 */141 142 addModule : function(module, args) {143 Express.settings[module.name] = {}144145 if ('init' in module) 146 module.init.apply(module, Express.argsArray(arguments, 1))147148 if ('settings' in module) {149 if (!module.name) throw 'module name is required when using .settings'150 for (var name in module.settings)151 if (module.settings.hasOwnProperty(name))152 Express.settings[module.name][name] = module.settings[name]153 }154 155 if ('utilities' in module)156 for (var name in module.utilities)157 if (module.utilities.hasOwnProperty(name))158 Express.utilities[name] = module.utilities[name]159 160 Express.modules.push(module)161 },162 163 /**164 * Start Express; binding to _host_ / _port_.165 *166 * @param {int} port167 * @param {string} host168 * @api public169 */170 171 start : function(port, host) {172 this.server.listen(port || 3000, host, this.server.callback)173 },174 175 server : {176 177 /**178 * Listen to _host_ / _port_ with _callback_.179 *180 * @param {int} port181 * @param {string} host182 * @param {function} callback183 * @api private184 */185 186 listen : function(port, host, callback) {187 node.http.createServer(callback).listen(port, host)188 puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')189 },190 191 /**192 * Request callback.193 *194 * @param {object} request195 * @param {object} response196 * @api private197 */198 199 callback : function(request, response){200 request.body = request.body || ''201 request.setBodyEncoding('utf8')202 request.addListener('body', function(chunk) { request.body += chunk })203 request.addListener('complete', function(){204 Express.home = Express.settings.basepath205 Express.response.body = null206 Express.response.status = 200207 Express.request = request208 request.headers = Express.arrayToHash(request.headers)209 request.uri.params = Express.parseNestedParams(request.uri.params)210 request.uri.path = Express.normalizePath(request.uri.path)211 Express.hook('onRequest')212 try { Express.response.body = Express.callRouteFor(request) }213 catch (e) { Express.fail(e) }214 Express.hook('onResponse')215 response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))216 response.sendBody(Express.response.body || '')217 response.finish()218 })219 }220 },221 222 /**223 * Fail Express with exception _e_.224 *225 * @param {object} e226 * @api private227 */228229 fail : function(e) {230 this.hook('onFailure', e)231 if (e.constructor == Express.Halt) return232 this.header('Content-Type', 'text/plain')233 this.response.body = e.message ? e.name + ': ' + e.message : e.toString()234 this.response.status = 500235 },236 237 /**238 * Return an associative array generated239 * from the key / value pairs in _hash_.240 *241 * @param {hash} hash242 * @return {array}243 * @api public244 */245 246 hashToArray : function(hash) {247 var array = []248 for (var key in hash)249 if (hash.hasOwnProperty(key))250 array.push([key, hash[key]])251 return array252 },253 254 /**255 * Return hash generated from an256 * associative array.257 *258 * @param {array} array259 * @return {hash}260 * @api public261 */262 263 arrayToHash : function(array) {264 var hash = {}265 for (i = 0, len = array.length; i < len; ++i)266 hash[array[i][0].toLowerCase()] = array[i][1]267 return hash268 },269 270 /**271 * JSON encode _object_272 *273 * @param {mixed} object274 * @return {string}275 * @api public276 */277 278 jsonEncode : function(object) {279 return JSON.stringify(object)280 },281 282 /**283 * JSON decode _string_.284 *285 * @param {string} string286 * @return {mixed}287 * @api public288 */289 290 jsonDecode : function(string) {291 return JSON.parse(string)292 },293 294 /**295 * Redirect to _url_.296 *297 * @param {string} url298 * @api public299 */300 301 redirect : function(url) {302 this.header('Location', url)303 this.respond("Page or file has moved to `" + url + "'", 'Moved Temporarily')304 },305 306 /**307 * Set response status to _value_. Where value may be308 * a case-insensitive string such as 'Not Found', 'forbidden',309 * or a numeric HTTP response status code.310 *311 * @param {int, string} value312 * @return {int}313 * @api public314 */315 316 status : function(value) {317 if (value == undefined) return318 if (typeof value == 'number') return this.response.status = value319 for (var code in node.http.STATUS_CODES)320 if (node.http.STATUS_CODES.hasOwnProperty(code))321 if (node.http.STATUS_CODES[code].toLowerCase() == value.toLowerCase())322 return this.response.status = parseInt(code)323 },324325 /**326 * Return path segment _n_.327 *328 * @param {int} n329 * @return {string}330 * @api public331 */332 333 arg : function(n) {334 return this.request.uri.path.split('/')[n]335 },336 337 /**338 * Set response _status_ and _body_.339 *340 * @param {string} body341 * @param {string, int} status342 * @api public343 */344 345 respond : function(body, status) {346 this.response.body = body347 this.status(status)348 throw new Express.Halt()349 },350 351 /**352 * Get or set response _name_ header.353 *354 * @param {string} name355 * @param {string} value356 * @return {string}357 * @api public358 */359 360 header : function(name, value) {361 return value ? 362 this.response.headers[name.toLowerCase()] = value :363 this.response.headers[name.toLowerCase()]364 },365 366 /**367 * Get request header _name_ optionally providing _default_368 * when _name_ is not present.369 *370 * @param {string} name371 * @param {string} default372 * @return {string}373 * @api public374 */375 376 requestHeader : function(name, defaultValue) {377 return this.request.headers[name.toLowerCase()] || defaultValue378 },379 380 /**381 * Return param _key_'s value or _defaultValue_ when382 * the param has not been set.383 *384 * @param {string} key385 * @param {mixed} defaultValue386 * @return {mixed}387 * @api public388 */389 390 param : function(key, defaultValue) {391 return this.request.uri.params[key] || defaultValue392 },393 394 /**395 * Parse params _string_ into a nested hash.396 *397 * @param {string} string398 * @return {hash}399 * @api public400 */401 402 parseParams : function(string) {403 var params = {}, pairs = string.split('&'), pair404 for (i = 0, len = pairs.length; i < len; ++i) {405 pair = pairs[i].split('=')406 params[pair[0]] = pair[1]407 }408 return this.parseNestedParams(params)409 },410 411 /**412 * Parse _params_, splitting { user[info][name] : 'tj' } into413 * { user : { info : { name : 'tj' }}}414 *415 * @param {hash} params416 * @return {hash}417 * @api public418 */419 420 parseNestedParams : function(params) {421 for (var key in params)422 if (params.hasOwnProperty(key))423 if (parts = key.split('['))424 if (parts.length > 1)425 for (i = 0, prop = params, len = parts.length; i < len; ++i) {426 var name = parts[i].replace(']', '')427 if (i == len - 1) {428 prop[name] = params[key]429 prop = params, delete params[key]430 }431 else {432 prop = prop[name] = prop[name] || {}433 }434 }435 436 return params437 },438 439 /**440 * Parse _cookie_ string into an object (hash).441 *442 * @param {string} cookie443 * @return {hash}444 * @api public445 */446 447 parseCookie : function(cookie) {448 var hash = {}449 if (!cookie) return hash450 var attrs = cookie.split(/\s*;\s*/)451 for (i = 0; i < attrs.length; ++i)452 hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])453 return hash454 },455 456 /**457 * Normalize a path. Strips trailing / leading whitespace458 * and slashes ('/').459 *460 * @param {string} path461 * @return {string}462 * @api public463 */464 465 normalizePath : function(path) {466 if (typeof path != 'string') return path467 return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')468 },469 470 /**471 * Normalize _path_. When a RegExp it is simply returned,472 * otherwise a string is converted to a regular expression473 * surrounded by ^$. So /user/:id/edit would become:474 *475 * \^/user/(.*?)\/edit\$/476 *477 * Each param key (:id) will be captured and placed in the478 * params array, so param('id') would give the string captured.479 *480 * @param {string} path481 * @return {regexp}482 * @api public483 */484 485 pathToRegexp : function(path) {486 Express.regexpKeys = []487 if (path.constructor == RegExp) return path488 path = path.replace(/:(\w+)/g, function(_, key){489 Express.regexpKeys.push(key)490 return '(.*?)'491 })492 return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')493 },494 495 /**496 * Escape RegExp _chars_ in _string_. Where _chars_ 497 * defaults to regular expression special characters.498 *499 * _chars_ should be a space delimited list of characters,500 * for example '[ ] ( )'.501 *502 * @param {string} string503 * @param {string} chars504 * @return {Type}505 * @api public506 */507 508 escapeRegexp : function(string, chars) {509 var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')510 return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')511 },512 513 /**514 * Return the contents of a function body.515 *516 * @param {function} body517 * @return {string}518 * @api public519 */520 521 contentsOf : function(body) {522 if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"523 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]524 },525 526 /**527 * Eval _string_ in context of Express.528 *529 * @param {string} string530 * @return {mixed}531 * @api public532 */533 534 eval : function(string) {535 return eval('with (Express){ with (Express.utilities){ ' + string + '}}')536 },537 538 /**539 * Escape special characters in _html_.540 *541 * @param {string} html542 * @return {string}543 * @api public544 */545 546 escape : function(html) {547 return html.548 replace(/&/g, '&').549 replace(/"/g, '"').550 replace(/</g, '<').551 replace(/>/g, '>')552 },553 554 /**555 * Convert native arguments object into an556 * array with optional _offset_.557 *558 * @param {arguments} args559 * @param {int} offset560 * @return {array}561 * @api public562 */563 564 argsArray : function(args, offset) {565 return Array.prototype.slice.call(args, offset)566 },567 568 /**569 * Check if _route_ matches provides the proper570 * encoding types listed in _request_'s Accept header.571 *572 * @param {hash} route573 * @param {hash} request574 * @return {bool}575 * @api private576 */577 578 routeProvides : function(route, request) {579 if (!route.options.provides) return true580 if (route.options.provides.constructor != Array) 581 route.options.provides = [route.options.provides]582 for (i = 0, len = route.options.provides.length; i < len; ++i)583 if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))584 return true585 return false586 },587 588 /**589 * Attept to match and call a route for 590 * the given _request_, returning the data591 * returned by the route callback.592 *593 * @param {object} request594 * @return {mixed}595 * @api private596 */597 598 callRouteFor : function(request) {599 var route = this.findRouteFor(request) || this.settings.defaultRoute600 if (route.keys)601 for (i = 0, len = route.keys.length; i < len; ++i) 602 this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null603 var body = this.eval(Express.contentsOf(route.callback))604 if (typeof body != 'string') 605 throw "route `" + route.method.toUpperCase() + ' ' + route.path + "' must return a string"606 return body607 },608 609 /**610 * Attemp to find and return a route matching _request_.611 *612 * @param {object} request613 * @return {object}614 * @api private615 */616 617 findRouteFor : function(request) {618 for (i = 0, len = this.routes.length; i < len; ++i)619 if (this.routeMatches(this.routes[i], request))620 return this.routes[i]621 },622 623 /**624 * Check if _route_ matches _request_625 *626 * @param {object} route627 * @param {object} request628 * @return {bool}629 * @api private630 */631 632 routeMatches : function(route, request) {633 if (request.method.toLowerCase() != route.method) return false634 switch (route.path.constructor) {635 case String: return route.path == request.uri.path636 case RegExp: return !! (Express.captures = request.uri.path.match(route.path))637 }638 },639 640 /**641 * Return a routing function for _method_.642 *643 * @param {string} method644 * @return {function}645 * @api private646 */647 648 routeFunctionFor : function(method) {649 return function(path, options, callback) {650 if (options.constructor == Function) callback = options, options = {}651 path = Express.pathToRegexp(Express.normalizePath(path))652 var route = {653 keys : Express.regexpKeys,654 path : path,655 method : method,656 options : options,657 callback : callback658 }659 Express.routes.push(route)660 Express.hook('onRouteAdded', route)661 }662 }663 }664 665 // --- Expose666 667 get = Express.routeFunctionFor('get')668 post = Express.routeFunctionFor('post')669 del = Express.routeFunctionFor('delete')670 put = Express.routeFunctionFor('put')671 use = Express.addModule672673 // --- Core Modules674 675 use(Express.BodyDecoder)676 use(Express.MethodOverride)677 use(Express.ContentLength)678 use(Express.DefaultContentType)679 use(Express.RedirectHelpers)680 681})()682683get('user', function(){684 'Foo'685})686687put('user', function(){688 p('PUT')689})690691del('user', function(){692 p('DELETE')693})694695// Express.start()