Skip to content
Myr

express.core.js

This file

Path

lib/express.core.js

728 lines · 17.6 KiB · JavaScript

Last changed by

Fixed whitespace from another devs commitsvisionmediabefore adoptionf623873

History of this file

Take it

12// Express - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34process.mixin(GLOBAL, require("sys"))5var http = require("http")67Express = { 8  version : '0.0.1',9  utilities : {},10  modules  : [],11  routes  : [],12  STATUS_CODES : {13    100 : 'Continue',14    101 : 'Switching Protocols',15    200 : 'OK',16    201 : 'Created',17    202 : 'Accepted',18    203 : 'Non-Authoritative Information',19    204 : 'No Content',20    205 : 'Reset Content',21    206 : 'Partial Content',22    300 : 'Multiple Choices',23    301 : 'Moved Permanently',24    302 : 'Moved Temporarily',25    303 : 'See Other',26    304 : 'Not Modified',27    305 : 'Use Proxy',28    400 : 'Bad Request',29    401 : 'Unauthorized',30    402 : 'Payment Required',31    403 : 'Forbidden',32    404 : 'Not Found',33    405 : 'Method Not Allowed',34    406 : 'Not Acceptable',35    407 : 'Proxy Authentication Required',36    408 : 'Request Time-out',37    409 : 'Conflict',38    410 : 'Gone',39    411 : 'Length Required',40    412 : 'Precondition Failed',41    413 : 'Request Entity Too Large',42    414 : 'Request-URI Too Large',43    415 : 'Unsupported Media Type',44    500 : 'Internal Server Error',45    501 : 'Not Implemented',46    502 : 'Bad Gateway',47    503 : 'Service Unavailable',48    504 : 'Gateway Time-out',49    505 : 'HTTP Version not supported'50  },51  52  // --- Halt53  54  Halt : function(){55    this.toString = function() {56      return 'Express.Halt'57    }58  },59  60  // --- Response61  62  response : {63    headers : {},64    cookie : {}65  },66  67  // --- Settings68  69  settings : {70    basepath : '/',71    defaultRoute : {72      callback : function() {73        Express.respond('Page or file cannot be found', 'Not Found')74      }75    }76  },77  78  // --- Modules79  80  RedirectHelpers : {81    init : function() {82      Express.home = Express.settings.basepath83    },84    85    onRequest : {86      'set back to referrer' : function() {87        Express.back = 88          Express.requestHeader('Referer') ||89            Express.requestHeader('Referrer')90      }91    }92  },93  94  ContentLength : {95    onResponse : {96      'set content length' : function() {97        Express.header('Content-Length', (Express.response.body || '').length)98      }99    }100  },101  102  DefaultContentType : {103    onRequest : {104      'set response content type to text/html' : function() {105        Express.header('Content-Type', 'text/html')106      }107    }108  },109  110  BodyDecoder : {111    onRequest : {112      'parse urlencoded bodies' : function() {113        switch (Express.requestHeader('Content-Type')) {114          case 'application/x-www-form-urlencoded':115            Express.request.uri.params = Express.parseParams(decodeURIComponent(Express.request.body))116            break117          118          case 'application/json':119            Express.request.uri.params = Express.jsonDecode(Express.request.body)120            break121        }122      }123    }124  },125  126  MethodOverride : {127    onRequest : {128      'set HTTP method to _method when present' : function() {129        if (method = Express.param('_method'))130          Express.request.method = method.toUpperCase()131      }132    }133  },134  135  Logger : {136    onResponse : {137      'output log data' : function(){138        puts('"' + Express.request.method + ' ' + Express.request.uri.path +139             ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)140      }141    }142  },143  144  /**145   * Invoke hook _name_ with _args_, returning146   * an array of return values.147   *148   * @param  {string} name149   * @param  {...} args150   * @return {array}151   * @api public152   */153  154  hook : function(name, args) {155    var results = []156    for (var i = 0, len = this.modules.length; i < len; ++i)157      for (var key in this.modules[i][name])158        results.push(this.modules[i][name][key].apply(this.modules[i], this.toArray(arguments, 1))) 159    return results160  },161  162  /**163   * Invoke hook _name_ with _immutable_ and _args_, returning164   * the _immutable_ variable once modified by each hook implementation.165   * When implementing these hooks, the function must return a value.166   *167   * @param  {string} name168   * @param  {mixed} immutable169   * @param  {...} args170   * @return {mixed}171   * @api public172   */173  174  hookImmutable : function(name, immutable, args) {175    for (var i = 0, len = this.modules.length; i < len; ++i)176      for (var key in this.modules[i][name])177        immutable = this.modules[i][name][key].call(this.modules[i], immutable)178    return immutable179  },180  181  /**182   * Add _module_.183   *184   * @param  {hash} module185   * @param  {...} args186   * @api public187   */188  189  addModule : function(module, args) {190    Express.settings[module.name] = {}191192    if ('init' in module) 193      module.init.apply(module, Express.toArray(arguments, 1))194195    if ('settings' in module) {196      if (!module.name) throw 'module name is required when using .settings'197      for (var name in module.settings)198        Express.settings[module.name][name] = module.settings[name]199    }200          201    if ('utilities' in module)202      for (var name in module.utilities)203        Express.utilities[name] = module.utilities[name]204    205    Express.modules.push(module)206  },207  208  /**209   * Start Express; binding to _host_ / _port_.210   *211   * @param {int} port212   * @param {string} host213   * @api public214   */215  216  start : function(port, host) {217    this.server.listen(port || 3000, host, this.server.callback)218  },219  220  server : {221    222    /**223     * Listen to _host_ / _port_ with _callback_.224     *225     * @param {int} port226     * @param {string} host227     * @param {function} callback228     * @api private229     */230    231    listen : function(port, host, callback) {232      http.createServer(callback).listen(port, host)233      puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')234    },235    236    /**237     * Request callback.238     *239     * @param  {object} request240     * @param  {object} response241     * @api private242     */243    244    callback : function(request, response){245      request.body = request.body || ''246      request.setBodyEncoding('utf8')247      request.addListener('body', function(chunk) { request.body += chunk })248      request.addListener('complete', function(){249        Express.home = Express.settings.basepath250        Express.response.body = null251        Express.response.status = 200252        Express.request = request253        Express.originalResponse = response254        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        if (Express.response.body) {261          Express.server.finished()262        }263      })264    },265  266    finished: function(body) {267      if (body) Express.response.body = body268      Express.hook('onResponse')269      Express.originalResponse.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))270      Express.originalResponse.sendBody(Express.response.body || '')271      Express.originalResponse.finish()272    }273  },274  275  /**276   * Fail Express with exception _e_.277   *278   * @param  {object} e279   * @api private280   */281282  fail : function(e) {283    this.hook('onFailure', e)284    if (e.constructor == Express.Halt) return285    this.header('Content-Type', 'text/plain')286    this.response.body = e.message ? e.name + ': ' + e.message : e.toString()287    this.response.status = 500288  },289  290  /**291   * Return an associative array generated292   * from the key / value pairs in _hash_.293   *294   * @param  {hash} hash295   * @return {array}296   * @api public297   */298  299  hashToArray : function(hash) {300    var array = []301    for (var key in hash)302      array.push([key, hash[key]])303    return array304  },305  306  /**307   * Return hash generated from an308   * associative array.309   *310   * @param  {array} array311   * @return {hash}312   * @api public313   */314  315  arrayToHash : function(array) {316    var hash = {}317    for (var i = 0, len = array.length; i < len; ++i)318      hash[array[i][0].toLowerCase()] = array[i][1]319    return hash320  },321  322  /**323   * JSON encode _object_324   *325   * @param  {mixed} object326   * @return {string}327   * @api public328   */329  330  jsonEncode : function(object) {331    return JSON.stringify(object)332  },333  334  /**335   * JSON decode _string_.336   *337   * @param  {string} string338   * @return {mixed}339   * @api public340   */341   342   jsonDecode : function(string) {343     return JSON.parse(string)344   },345   346  /**347   * Redirect to _uri_.348   *349   * @param  {string} uri350   * @api public351   */352  353  redirect : function(uri) {354    this.header('Location', uri)355    this.respond("Page or file has moved to `" + uri + "'", 'Moved Temporarily')356  },357  358  /**359   * Set response status to _value_. Where value may be360   * a case-insensitive string such as 'Not Found', 'forbidden',361   * or a numeric HTTP response status code.362   *363   * @param  {int, string} value364   * @return {int}365   * @api public366   */367  368  status : function(value) {369    if (value == undefined) return370    if (typeof value == 'number') return this.response.status = value371    for (var code in this.STATUS_CODES)372      if (this.STATUS_CODES[code].toLowerCase() == value.toLowerCase())373        return this.response.status = parseInt(code)374  },375376  /**377   * Return path segment _n_.378   *379   * @param  {int} n380   * @return {string}381   * @api public382   */383  384  arg : function(n) {385    return this.request.uri.path.split('/')[n]386  },387  388  /**389   * Set response _status_ and _body_.390   *391   * @param  {string} body392   * @param  {string, int} status393   * @api public394   */395  396  respond : function(body, status) {397    this.response.body = body398    this.status(status)399    throw new Express.Halt()400  },401  402  /**403   * Get or set response _name_ header.404   *405   * @param  {string} name406   * @param  {string} value407   * @return {string}408   * @api public409   */410  411  header : function(name, value) {412    return value ? 413      this.response.headers[name.toLowerCase()] = value :414        this.response.headers[name.toLowerCase()]415  },416  417  /**418   * Get request header _name_ optionally providing _default_419   * when _name_ is not present.420   *421   * @param  {string} name422   * @param  {string} default423   * @return {string}424   * @api public425   */426  427  requestHeader : function(name, defaultValue) {428    return this.request.headers[name.toLowerCase()] || defaultValue429  },430      431  /**432   * Return param _key_'s value or _defaultValue_ when433   * the param has not been set.434   *435   * @param  {string} key436   * @param  {mixed} defaultValue437   * @return {mixed}438   * @api public439   */440  441  param : function(key, defaultValue) {442    return this.request.uri.params[key] || defaultValue443  },444  445  /**446   * Parse params _string_ into a nested hash.447   *448   * @param  {string} string449   * @return {hash}450   * @api public451   */452  453  parseParams : function(string) {454    var params = {}, pairs = string.split('&'), pair455    for (var i = 0, len = pairs.length; i < len; ++i) {456      pair = pairs[i].split('=')457      params[pair[0]] = pair[1]458    }459    return this.parseNestedParams(params)460  },461  462  /**463   * Parse _params_, splitting { user[info][name] : 'tj' } into464   * { user : { info : { name : 'tj' }}}465   *466   * @param  {hash} params467   * @return {hash}468   * @api public469   */470  471  parseNestedParams : function(params) {472    for (var key in params)473      if (parts = key.split('['))474        if (parts.length > 1)475          for (var i = 0, prop = params, len = parts.length; i < len; ++i) {476            var name = parts[i].replace(']', '')477            if (i == len - 1) {478              prop[name] = params[key]479              prop = params, delete params[key]480            }481            else {482              prop = prop[name] = prop[name] || {}483            }484          }485              486    return params487  },488  489  /**490   * Parse _cookie_ string into an object (hash).491   *492   * @param  {string} cookie493   * @return {hash}494   * @api public495   */496  497  parseCookie : function(cookie) {498    var hash = {}499    if (!cookie) return hash500    var attrs = cookie.split(/\s*;\s*/)501    for (var i = 0; i < attrs.length; ++i)502      hash[attrs[i].split('=')[0]] = decodeURIComponent(attrs[i].split('=')[1])503    return hash504  },505  506  /**507   * Normalize a path. Strips trailing / leading whitespace508   * and slashes ('/').509   *510   * @param  {string} path511   * @return {string}512   * @api public513   */514  515  normalizePath : function(path) {516    if (typeof path != 'string') return path517    return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')518  },519  520  /**521   * Normalize _path_. When a RegExp it is simply returned,522   * otherwise a string is converted to a regular expression523   * surrounded by ^$. So /user/:id/edit would become:524   *525   * \^/user/(.*?)\/edit\$/526   *527   * Each param key (:id) will be captured and placed in the528   * params array, so param('id') would give the string captured.529   *530   * @param  {string} path531   * @return {regexp}532   * @api public533   */534  535  pathToRegexp : function(path) {536    Express.regexpKeys = []537    if (path.constructor == RegExp) return path538    path = path.replace(/:(\w+)/g, function(_, key){539      Express.regexpKeys.push(key)540      return '(.*?)'541    })542    return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')543  },544  545  /**546   * Escape RegExp _chars_ in _string_. Where _chars_ 547   * defaults to regular expression special characters.548   *549   * _chars_ should be a space delimited list of characters,550   * for example '[ ] ( )'.551   *552   * @param  {string} string553   * @param  {string} chars554   * @return {Type}555   * @api public556   */557  558  escapeRegexp : function(string, chars) {559    var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')560    return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')561  },562  563  /**564   * Return the contents of a function body.565   *566   * @param  {function} body567   * @return {string}568   * @api public569   */570  571  contentsOf : function(body) {572    if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"573    return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]574  },575  576  /**577   * Eval _string_ in context of Express.578   *579   * @param  {string} string580   * @return {mixed}581   * @api public582   */583  584  eval : function(string) {585    return eval('with (Express){ with (Express.utilities){ ' + string + '}}')586  },587      588  /**589   * Escape special characters in _html_.590   *591   * @param  {string} html592   * @return {string}593   * @api public594   */595  596  escape : function(html) {597    return html.598      replace(/&/g, '&amp;').599      replace(/"/g, '&quot;').600      replace(/</g, '&lt;').601      replace(/>/g, '&gt;')602  },603  604  /**605   * Convert native array-like objects into an606   * array with optional _offset_.607   *608   * @param  {object} arr609   * @param  {int} offset610   * @return {array}611   * @api public612   */613  614  toArray : function(arr, offset) {615    return Array.prototype.slice.call(arr, offset)616  },617  618  /**619   * Check if _route_ matches provides the proper620   * encoding types listed in _request_'s Accept header.621   *622   * @param  {hash} route623   * @param  {hash} request624   * @return {bool}625   * @api private626   */627  628  routeProvides : function(route, request) {629    if (!route.options.provides) return true630    if (route.options.provides.constructor != Array) 631      route.options.provides = [route.options.provides]632    for (var i = 0, len = route.options.provides.length; i < len; ++i)633      if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))634        return true635    return false636  },637  638  /**639   * Attept to match and call a route for 640   * the given _request_, returning the data641   * returned by the route callback.642   *643   * @param  {object} request644   * @return {mixed}645   * @api private646   */647  648  callRouteFor : function(request) {649    var route = this.findRouteFor(request) || this.settings.defaultRoute650    if (route.keys)651      for (var i = 0, len = route.keys.length; i < len; ++i) 652        this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null653    var body = this.eval(Express.contentsOf(route.callback))654    if (typeof body != 'string') body = null655    return body656  },657  658  /**659   * Attempt to find and return a route matching _request_.660   *661   * @param  {object} request662   * @return {object}663   * @api private664   */665  666  findRouteFor : function(request) {667    for (var i = 0, len = this.routes.length; i < len; ++i)668      if (this.routeMatches(this.routes[i], request))669        return this.routes[i]670  },671  672  /**673   * Check if _route_ matches _request_674   *675   * @param  {object} route676   * @param  {object} request677   * @return {bool}678   * @api private679   */680  681  routeMatches : function(route, request) {682    if (request.method.toLowerCase() != route.method) return false683    switch (route.path.constructor) {684      case String: return route.path == request.uri.path685      case RegExp: return !! (Express.captures = request.uri.path.match(route.path))686    }687  },688  689  /**690   * Return a routing function for _method_.691   *692   * @param  {string} method693   * @return {function}694   * @api private695   */696  697  routeFunctionFor : function(method) {698    return function(path, options, callback) {699      if (options.constructor == Function) callback = options, options = {}700      path = Express.pathToRegexp(Express.normalizePath(path))701      var route = {702        keys : Express.regexpKeys,703        path : path,704        method : method,705        options : options,706        callback : callback707      }708      Express.routes.push(route)709      Express.hook('onRouteAdded', route)710    }711  }712}713714// --- Routing API715716get = Express.routeFunctionFor('get')717post = Express.routeFunctionFor('post')718del = Express.routeFunctionFor('delete')719put = Express.routeFunctionFor('put')720use = Express.addModule721722// --- Core Modules723724use(Express.BodyDecoder)725use(Express.MethodOverride)726use(Express.ContentLength)727use(Express.DefaultContentType)728use(Express.RedirectHelpers)