express.core.js
This file
Path
lib/express.core.js
595 lines · 15.3 KiB · JavaScript
Last changed by
Break -> Halt [#11]visionmediabefore adoptionc61372b
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 routes : [],8 9 // --- Halt10 11 Halt : function(){12 this.toString = function() {13 return 'Express.Halt'14 }15 },16 17 // --- Response18 19 response : {20 headers : {},21 cookie : {}22 },23 24 // --- Settings25 26 settings : {27 basepath : '/',28 29 cookie : {30 maxAge : 360031 },32 33 defaultRoute : {34 callback : function() {35 Express.respond('Page or file cannot be found', 'Not Found')36 }37 }38 },39 40 hookCallbacks : {41 request : [42 43 // Redirect helpers44 45 function (request, response) { 46 Express.home = Express.settings.basepath47 },48 49 // Cookie parsing50 51 function (request, response) {52 Express.response.cookie = request.cookie = Express.parseCookie(request.headers['Cookie'])53 }54 ],55 56 response : [57 58 // Content length59 60 function(request, response) {61 Express.header('Content-Length', (Express.response.body || '').length)62 }63 ]64 },65 66 /**67 * Invoke hook _name_ with _args_.68 *69 * @param {string} name70 * @param {...} args71 * @api public72 */73 74 hook : function(name, args) {75 if (this.hookCallbacks[name])76 for (i = 0, len = this.hookCallbacks[name].length; i < len; ++i)77 if (typeof this.hookCallbacks[name][i] == 'function')78 this.hookCallbacks[name][i].apply(this, this.argsArray(arguments, 1))79 },80 81 /**82 * Add middlware _callback_ for hook _name_.83 *84 * @param {string} name85 * @param {function} callback86 * @api public87 */88 89 use : function(name, callback) {90 Express.hookCallbacks[name].push(callback)91 },92 93 /**94 * Start Express; binding to _host_ / _port_.95 *96 * @param {int} port97 * @param {string} host98 * @api public99 */100 101 start : function(port, host) {102 this.server.listen(port || 3000, host, this.server.callback)103 },104 105 server : {106 107 /**108 * Listen to _host_ / _port_ with _callback_.109 *110 * @param {int} port111 * @param {string} host112 * @param {function} callback113 * @api private114 */115 116 listen : function(port, host, callback) {117 node.http.createServer(callback).listen(port, host)118 puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')119 },120 121 /**122 * Request callback.123 *124 * @param {object} request125 * @param {object} response126 * @api private127 */128 129 callback : function(request, response){130 Express.home = Express.settings.basepath131 Express.response.body = null132 Express.response.status = 200133 Express.request = request134 request.headers = Express.arrayToHash(request.headers)135 Express.hook('request', request, response)136 request.uri.params = Express.parseNestedParams(request.uri.params)137 request.uri.path = Express.normalizePath(request.uri.path)138 try { Express.response.body = Express.callRouteFor(request) }139 catch (e) { Express.fail(e) }140 Express.prepareCookie()141 Express.hook('response', Express.request, Express.response)142 response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))143 response.sendBody(Express.response.body || '')144 response.finish()145 }146 },147 148 /**149 * Fail Express with exception _e_.150 *151 * @param {object} e152 * @api private153 */154155 fail : function(e) {156 if (e.constructor == Express.Halt) return157 this.header('Content-Type', 'text/plain')158 this.response.body = e.message ? e.name + ': ' + e.message : e.toString()159 this.response.status = 500160 },161 162 prepareCookie : function() {163 var cookie = []164 for (var key in this.response.cookie)165 if (this.response.cookie.hasOwnProperty(key))166 cookie.push(key + '=' + this.response.cookie[key])167 if (cookie.length)168 this.header('Set-Cookie', cookie.join('; '))169 },170 171 /**172 * Return an associative array generated173 * from the key / value pairs in _hash_.174 *175 * @param {hash} hash176 * @return {array}177 * @api public178 */179 180 hashToArray : function(hash) {181 var array = []182 for (var key in hash)183 if (hash.hasOwnProperty(key))184 array.push([key, hash[key]])185 return array186 },187 188 /**189 * Return hash generated from an190 * associative array.191 *192 * @param {array} array193 * @return {hash}194 * @api public195 */196 197 arrayToHash : function(array) {198 var hash = {}199 for (i = 0, len = array.length; i < len; ++i)200 hash[array[i][0].toLowerCase()] = array[i][1]201 return hash202 },203 204 /**205 * JSON encode _object_206 *207 * @param {mixed} object208 * @return {string}209 * @api public210 */211 212 jsonEncode : function(object) {213 return JSON.stringify(object)214 },215 216 /**217 * JSON decode _string_.218 *219 * @param {string} string220 * @return {mixed}221 * @api public222 */223 224 jsonDecode : function(string) {225 return JSON.parse(string)226 },227 228 /**229 * Redirect to _url_.230 *231 * @param {string} url232 * @api public233 */234 235 redirect : function(url) {236 this.header('Location', url)237 this.respond("Page or file has moved to `" + url + "'", 'Moved Temporarily')238 },239 240 /**241 * Set response status to _value_. Where value may be242 * a case-insensitive string such as 'Not Found', 'forbidden',243 * or a numeric HTTP response status code.244 *245 * @param {int, string} value246 * @return {int}247 * @api public248 */249 250 status : function(value) {251 if (value == undefined) return252 if (typeof value == 'number') return this.response.status = value253 for (var code in node.http.STATUS_CODES)254 if (node.http.STATUS_CODES.hasOwnProperty(code))255 if (node.http.STATUS_CODES[code].toLowerCase() == value.toLowerCase())256 return this.response.status = parseInt(code)257 },258 259 /**260 * Set response _status_ and _body_.261 *262 * @param {string} body263 * @param {string, int} status264 * @api public265 */266 267 respond : function(body, status) {268 this.response.body = body269 this.status(status)270 throw new Express.Halt()271 },272 273 /**274 * Sets _name_ header to _value_. When _value_275 * is not present the request header will be returned.276 *277 * @param {string} name278 * @param {string} value279 * @api public280 */281 282 header : function(name, value) {283 name = name.toLowerCase()284 return value ? this.response.headers[name] = value :285 this.request.headers[name] || this.response.headers[name]286 },287 288 /**289 * Return param _key_'s value or _defaultValue_ when290 * the param has not been set.291 *292 * @param {string} key293 * @param {mixed} defaultValue294 * @return {mixed}295 * @api public296 */297 298 param : function(key, defaultValue) {299 return this.request.uri.params[key] || defaultValue300 },301 302 303 /**304 * Return cookie _key_. When _value_ is present305 * then a response cookie field will be set.306 *307 * @param {string} key308 * @param {string} value309 * @return {string, hash}310 * @api public311 */312313 cookie : function(key, value) {314 return value ? this.response.cookie[key] = value :315 this.response.cookie[key]316 },317 318 /**319 * Parse _params_, splitting { user[info][name] : 'tj' } into320 * { user : { info : { name : 'tj' }}}321 *322 * @param {hash} params323 * @return {hash}324 * @api public325 */326 327 parseNestedParams : function(params) {328 for (var key in params)329 if (params.hasOwnProperty(key))330 if (parts = key.split('['))331 if (parts.length > 1)332 for (i = 0, prop = params, len = parts.length; i < len; ++i) {333 if (i == len - 1) {334 var name = parts[i].replace(']', '')335 prop[name] = params[key]336 prop = params, delete params[key]337 }338 else {339 var name = parts[i].replace(']', '')340 prop = prop[name] = prop[name] || {}341 }342 }343 344 return params345 },346 347 /**348 * Parse _cookie_ string into an object (hash).349 *350 * @param {string} cookie351 * @return {hash}352 * @api public353 */354 355 parseCookie : function(cookie) {356 var hash = {}357 if (!cookie) return hash358 var attrs = cookie.split(/\s*;\s*/)359 for (i = 0; i < attrs.length; ++i)360 hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])361 return hash362 },363 364 /**365 * Normalize a path. Strips trailing / leading whitespace366 * and slashes ('/').367 *368 * @param {string} path369 * @return {string}370 * @api public371 */372 373 normalizePath : function(path) {374 if (typeof path != 'string') return path375 return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')376 },377 378 /**379 * Normalize _path_. When a RegExp it is simply returned,380 * otherwise a string is converted to a regular expression381 * surrounded by ^$. So /user/:id/edit would become:382 *383 * \^/user/(.*?)\/edit\$/384 *385 * Each param key (:id) will be captured and placed in the386 * params array, so param('id') would give the string captured.387 *388 * @param {string} path389 * @return {regexp}390 * @api public391 */392 393 pathToRegexp : function(path) {394 Express.regexpKeys = []395 if (path.constructor == RegExp) return path396 path = path.replace(/:(\w+)/g, function(_, key){397 Express.regexpKeys.push(key)398 return '(.*?)'399 })400 return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')401 },402 403 /**404 * Escape RegExp _chars_ in _string_. Where _chars_ 405 * defaults to regular expression special characters.406 *407 * _chars_ should be a space delimited list of characters,408 * for example '[ ] ( )'.409 *410 * @param {string} string411 * @param {string} chars412 * @return {Type}413 * @api public414 */415 416 escapeRegexp : function(string, chars) {417 var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')418 return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')419 },420 421 /**422 * Return the contents of a function body.423 *424 * @param {function} body425 * @return {string}426 * @api public427 */428 429 contentsOf : function(body) {430 if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"431 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]432 },433 434 /**435 * Eval _string_ in context of Express.436 *437 * @param {string} string438 * @return {mixed}439 * @api public440 */441 442 eval : function(string) {443 return eval('with (Express){' + string + '}')444 },445 446 /**447 * Escape special characters in _html_.448 *449 * @param {string} html450 * @return {string}451 * @api public452 */453 454 escape : function(html) {455 return html.456 replace(/&/g, '&').457 replace(/"/g, '"').458 replace(/</g, '<').459 replace(/>/g, '>')460 },461 462 /**463 * Convert native arguments object into an464 * array with optional _offset_.465 *466 * @param {arguments} args467 * @param {int} offset468 * @return {array}469 * @api public470 */471 472 argsArray : function(args, offset) {473 return Array.prototype.slice.call(args, offset)474 },475 476 /**477 * Check if _route_ matches provides the proper478 * encoding types listed in _request_'s Accept header.479 *480 * @param {hash} route481 * @param {hash} request482 * @return {bool}483 * @api private484 */485 486 routeProvides : function(route, request) {487 if (!route.options.provides) return true488 if (route.options.provides.constructor != Array) 489 route.options.provides = [route.options.provides]490 for (i = 0, len = route.options.provides.length; i < len; ++i)491 if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))492 return true493 return false494 },495 496 /**497 * Attept to match and call a route for 498 * the given _request_, returning the data499 * returned by the route callback.500 *501 * @param {object} request502 * @return {mixed}503 * @api private504 */505 506 callRouteFor : function(request) {507 var route = this.findRouteFor(request) || this.settings.defaultRoute508 if (route.keys)509 for (i = 0, len = route.keys.length; i < len; ++i) 510 this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null511 return this.eval(Express.contentsOf(route.callback)).toString()512 },513 514 /**515 * Attemp to find and return a route matching _request_.516 *517 * @param {object} request518 * @return {object}519 * @api private520 */521 522 findRouteFor : function(request) {523 for (i = 0, len = this.routes.length; i < len; ++i)524 if (this.routeMatches(this.routes[i], request))525 return this.routes[i]526 },527 528 /**529 * Check if _route_ matches _request_530 *531 * @param {object} route532 * @param {object} request533 * @return {bool}534 * @api private535 */536 537 routeMatches : function(route, request) {538 if (request.method.toLowerCase() != route.method) return false539 switch (route.path.constructor) {540 case String: return route.path == request.uri.path541 case RegExp: return !! (Express.captures = request.uri.path.match(route.path))542 }543 },544 545 /**546 * Return a routing function for _method_.547 *548 * @param {string} method549 * @return {function}550 * @api private551 */552 553 routeFunctionFor : function(method) {554 return function(path, options, callback) {555 if (options.constructor == Function) callback = options, options = {}556 path = Express.pathToRegexp(Express.normalizePath(path))557 Express.routes.push({558 keys : Express.regexpKeys,559 path : path,560 method : method,561 options : options,562 callback : callback563 })564 }565 },566 567 readFile : function(path, callback, errorCallback) {568 var promise = node.fs.cat(path, "utf8")569 errorCallback = errorCallback || function(){570 throw "failed to read file `" + path + "'"571 }572 promise.addCallback(callback)573 promise.addErrback(errorCallback)574 },575 576 parseView : function(contents, context) {577 578 },579 580 display : function(path) {581 582 },583 584 Logger : function(request, response){585 puts('"' + request.method + ' /' + request.uri.path + ' HTTP/' + request.httpVersion + '" - ' + Express.response.status)586 }587 }588 589 get = Express.routeFunctionFor('get')590 post = Express.routeFunctionFor('post')591 del = Express.routeFunctionFor('delete')592 put = Express.routeFunctionFor('put')593 use = Express.use594 595})()