Skip to content
Myr

express.core.js

This file

Path

lib/express.core.js

734 lines · 19.0 KiB · JavaScript

Last changed by

Asynchronous handlers working.csausdevbefore adoption80328f9

History of this file

Take 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		  Express.originalResponse = response255          request.headers = Express.arrayToHash(request.headers)256          request.uri.params = Express.parseNestedParams(request.uri.params)257          request.uri.path = Express.normalizePath(request.uri.path)258          Express.hook('onRequest')259          try { Express.response.body = Express.callRouteFor(request) }260          catch (e) { Express.fail(e) }261		  262		  if (Express.response.body) {263			  Express.server.finished()264		  }265        })266      },267	  268	  finished: function(body) {269		  if (body) Express.response.body = body270          Express.hook('onResponse')271          Express.originalResponse.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))272          Express.originalResponse.sendBody(Express.response.body || '')273          Express.originalResponse.finish()274	  }275	  276    },277    278    /**279     * Fail Express with exception _e_.280     *281     * @param  {object} e282     * @api private283     */284285    fail : function(e) {286      this.hook('onFailure', e)287      if (e.constructor == Express.Halt) return288      this.header('Content-Type', 'text/plain')289      this.response.body = e.message ? e.name + ': ' + e.message : e.toString()290      this.response.status = 500291    },292    293    /**294     * Return an associative array generated295     * from the key / value pairs in _hash_.296     *297     * @param  {hash} hash298     * @return {array}299     * @api public300     */301    302    hashToArray : function(hash) {303      var array = []304      for (var key in hash)305        array.push([key, hash[key]])306      return array307    },308    309    /**310     * Return hash generated from an311     * associative array.312     *313     * @param  {array} array314     * @return {hash}315     * @api public316     */317    318    arrayToHash : function(array) {319      var hash = {}320      for (var i = 0, len = array.length; i < len; ++i)321        hash[array[i][0].toLowerCase()] = array[i][1]322      return hash323    },324    325    /**326     * JSON encode _object_327     *328     * @param  {mixed} object329     * @return {string}330     * @api public331     */332    333    jsonEncode : function(object) {334      return JSON.stringify(object)335    },336    337    /**338     * JSON decode _string_.339     *340     * @param  {string} string341     * @return {mixed}342     * @api public343     */344     345     jsonDecode : function(string) {346       return JSON.parse(string)347     },348     349    /**350     * Redirect to _uri_.351     *352     * @param  {string} uri353     * @api public354     */355    356    redirect : function(uri) {357      this.header('Location', uri)358      this.respond("Page or file has moved to `" + uri + "'", 'Moved Temporarily')359    },360    361    /**362     * Set response status to _value_. Where value may be363     * a case-insensitive string such as 'Not Found', 'forbidden',364     * or a numeric HTTP response status code.365     *366     * @param  {int, string} value367     * @return {int}368     * @api public369     */370    371    status : function(value) {372      if (value == undefined) return373      if (typeof value == 'number') return this.response.status = value374      for (var code in this.STATUS_CODES)375        if (this.STATUS_CODES[code].toLowerCase() == value.toLowerCase())376          return this.response.status = parseInt(code)377    },378379    /**380     * Return path segment _n_.381     *382     * @param  {int} n383     * @return {string}384     * @api public385     */386    387    arg : function(n) {388      return this.request.uri.path.split('/')[n]389    },390    391    /**392     * Set response _status_ and _body_.393     *394     * @param  {string} body395     * @param  {string, int} status396     * @api public397     */398    399    respond : function(body, status) {400      this.response.body = body401      this.status(status)402      throw new Express.Halt()403    },404    405    /**406     * Get or set response _name_ header.407     *408     * @param  {string} name409     * @param  {string} value410     * @return {string}411     * @api public412     */413    414    header : function(name, value) {415      return value ? 416        this.response.headers[name.toLowerCase()] = value :417          this.response.headers[name.toLowerCase()]418    },419    420    /**421     * Get request header _name_ optionally providing _default_422     * when _name_ is not present.423     *424     * @param  {string} name425     * @param  {string} default426     * @return {string}427     * @api public428     */429    430    requestHeader : function(name, defaultValue) {431      return this.request.headers[name.toLowerCase()] || defaultValue432    },433        434    /**435     * Return param _key_'s value or _defaultValue_ when436     * the param has not been set.437     *438     * @param  {string} key439     * @param  {mixed} defaultValue440     * @return {mixed}441     * @api public442     */443    444    param : function(key, defaultValue) {445      return this.request.uri.params[key] || defaultValue446    },447    448    /**449     * Parse params _string_ into a nested hash.450     *451     * @param  {string} string452     * @return {hash}453     * @api public454     */455    456    parseParams : function(string) {457      var params = {}, pairs = string.split('&'), pair458      for (var i = 0, len = pairs.length; i < len; ++i) {459        pair = pairs[i].split('=')460        params[pair[0]] = pair[1]461      }462      return this.parseNestedParams(params)463    },464    465    /**466     * Parse _params_, splitting { user[info][name] : 'tj' } into467     * { user : { info : { name : 'tj' }}}468     *469     * @param  {hash} params470     * @return {hash}471     * @api public472     */473    474    parseNestedParams : function(params) {475      for (var key in params)476        if (parts = key.split('['))477          if (parts.length > 1)478            for (var i = 0, prop = params, len = parts.length; i < len; ++i) {479              var name = parts[i].replace(']', '')480              if (i == len - 1) {481                prop[name] = params[key]482                prop = params, delete params[key]483              }484              else {485                prop = prop[name] = prop[name] || {}486              }487            }488                489      return params490    },491    492    /**493     * Parse _cookie_ string into an object (hash).494     *495     * @param  {string} cookie496     * @return {hash}497     * @api public498     */499    500    parseCookie : function(cookie) {501      var hash = {}502      if (!cookie) return hash503      var attrs = cookie.split(/\s*;\s*/)504      for (var i = 0; i < attrs.length; ++i)505        hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])506      return hash507    },508    509    /**510     * Normalize a path. Strips trailing / leading whitespace511     * and slashes ('/').512     *513     * @param  {string} path514     * @return {string}515     * @api public516     */517    518    normalizePath : function(path) {519      if (typeof path != 'string') return path520      return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')521    },522    523    /**524     * Normalize _path_. When a RegExp it is simply returned,525     * otherwise a string is converted to a regular expression526     * surrounded by ^$. So /user/:id/edit would become:527     *528     * \^/user/(.*?)\/edit\$/529     *530     * Each param key (:id) will be captured and placed in the531     * params array, so param('id') would give the string captured.532     *533     * @param  {string} path534     * @return {regexp}535     * @api public536     */537    538    pathToRegexp : function(path) {539      Express.regexpKeys = []540      if (path.constructor == RegExp) return path541      path = path.replace(/:(\w+)/g, function(_, key){542        Express.regexpKeys.push(key)543        return '(.*?)'544      })545      return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')546    },547    548    /**549     * Escape RegExp _chars_ in _string_. Where _chars_ 550     * defaults to regular expression special characters.551     *552     * _chars_ should be a space delimited list of characters,553     * for example '[ ] ( )'.554     *555     * @param  {string} string556     * @param  {string} chars557     * @return {Type}558     * @api public559     */560    561    escapeRegexp : function(string, chars) {562      var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')563      return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')564    },565    566    /**567     * Return the contents of a function body.568     *569     * @param  {function} body570     * @return {string}571     * @api public572     */573    574    contentsOf : function(body) {575      if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"576      return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]577    },578    579    /**580     * Eval _string_ in context of Express.581     *582     * @param  {string} string583     * @return {mixed}584     * @api public585     */586    587    eval : function(string) {588      return eval('with (Express){ with (Express.utilities){ ' + string + '}}')589    },590        591    /**592     * Escape special characters in _html_.593     *594     * @param  {string} html595     * @return {string}596     * @api public597     */598    599    escape : function(html) {600      return html.601        replace(/&/g, '&amp;').602        replace(/"/g, '&quot;').603        replace(/</g, '&lt;').604        replace(/>/g, '&gt;')605    },606    607    /**608     * Convert native arguments object into an609     * array with optional _offset_.610     *611     * @param  {arguments} args612     * @param  {int} offset613     * @return {array}614     * @api public615     */616    617    argsArray : function(args, offset) {618      return Array.prototype.slice.call(args, offset)619    },620    621    /**622     * Check if _route_ matches provides the proper623     * encoding types listed in _request_'s Accept header.624     *625     * @param  {hash} route626     * @param  {hash} request627     * @return {bool}628     * @api private629     */630    631    routeProvides : function(route, request) {632      if (!route.options.provides) return true633      if (route.options.provides.constructor != Array) 634        route.options.provides = [route.options.provides]635      for (var i = 0, len = route.options.provides.length; i < len; ++i)636        if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))637          return true638      return false639    },640    641    /**642     * Attept to match and call a route for 643     * the given _request_, returning the data644     * returned by the route callback.645     *646     * @param  {object} request647     * @return {mixed}648     * @api private649     */650    651    callRouteFor : function(request) {652      var route = this.findRouteFor(request) || this.settings.defaultRoute653      if (route.keys)654        for (var i = 0, len = route.keys.length; i < len; ++i) 655          this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null656      var body = this.eval(Express.contentsOf(route.callback))657      if (typeof body != 'string') body = null658      return body659    },660    661    /**662     * Attempt to find and return a route matching _request_.663     *664     * @param  {object} request665     * @return {object}666     * @api private667     */668    669    findRouteFor : function(request) {670      for (var i = 0, len = this.routes.length; i < len; ++i)671        if (this.routeMatches(this.routes[i], request))672          return this.routes[i]673    },674    675    /**676     * Check if _route_ matches _request_677     *678     * @param  {object} route679     * @param  {object} request680     * @return {bool}681     * @api private682     */683    684    routeMatches : function(route, request) {685      if (request.method.toLowerCase() != route.method) return false686      switch (route.path.constructor) {687        case String: return route.path == request.uri.path688        case RegExp: return !! (Express.captures = request.uri.path.match(route.path))689      }690    },691    692    /**693     * Return a routing function for _method_.694     *695     * @param  {string} method696     * @return {function}697     * @api private698     */699    700    routeFunctionFor : function(method) {701      return function(path, options, callback) {702        if (options.constructor == Function) callback = options, options = {}703        path = Express.pathToRegexp(Express.normalizePath(path))704        var route = {705          keys : Express.regexpKeys,706          path : path,707          method : method,708          options : options,709          callback : callback710        }711        Express.routes.push(route)712        Express.hook('onRouteAdded', route)713      }714    }715  }716  717  // --- Expose718  719  get = Express.routeFunctionFor('get')720  post = Express.routeFunctionFor('post')721  del = Express.routeFunctionFor('delete')722  put = Express.routeFunctionFor('put')723  use = Express.addModule724725  // --- Core Modules726  727  use(Express.BodyDecoder)728  use(Express.MethodOverride)729  use(Express.ContentLength)730  use(Express.DefaultContentType)731  use(Express.RedirectHelpers)732    733})()734