Skip to content
Myr

express.core.js

This file

Path

lib/express.core.js

672 lines · 17.3 KiB · JavaScript

Last changed by

Added BodyDecoder specvisionmediabefore adoption461337a

History of this file

Take 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          if (Express.requestHeader('Content-Type') == 'application/x-www-form-urlencoded')65            Express.request.uri.params = Express.parseParams(unescape(Express.request.body))66        }67      }68    },69    70    FauxMethod : {71      onRequest : {72        'set HTTP method to _method when present' : function() {73          if (method = Express.param('_method'))74            Express.request.method = method.toUpperCase()75        }76      }77    },78    79    Logger : {80      onRequest : {81        'output log data' : function(){82          puts('"' + Express.request.method + ' ' + Express.request.uri.path +83               ' HTTP/' + Express.request.httpVersion + '" - ' + Express.response.status)84        }85      }86    },87    88    /**89     * Invoke hook _name_ with _args_, returning90     * an array of return values.91     *92     * @param  {string} name93     * @param  {...} args94     * @return {array}95     * @api public96     */97    98    hook : function(name, args) {99      var results = []100      for (i = 0, len = this.modules.length; i < len; ++i)101        for (var key in this.modules[i][name])102          if (this.modules[i][name].hasOwnProperty(key))103            results.push(this.modules[i][name][key].apply(this.modules[i], this.argsArray(arguments, 1))) 104      return results105    },106    107    /**108     * Invoke hook _name_ with _immutable_ and _args_, returning109     * the _immutable_ variable once modified by each hook implementation.110     * When implementing these hooks, the function must return a value.111     *112     * @param  {string} name113     * @param  {mixed} immutable114     * @param  {...} args115     * @return {mixed}116     * @api public117     */118    119    hookImmutable : function(name, immutable, args) {120      for (i = 0, len = this.modules.length; i < len; ++i)121        for (var key in this.modules[i][name])122          if (this.modules[i][name].hasOwnProperty(key))123            immutable = this.modules[i][name][key].call(this.modules[i], immutable)124      return immutable125    },126    127    /**128     * Add _module_.129     *130     * @param  {hash} module131     * @api public132     */133    134    addModule : function(module) {135      Express.settings[module.name] = {}136137      if ('init' in module) 138        module.init.call(module)139140      if ('settings' in module) {141        if (!module.name) throw 'module name is required when using .settings'142        for (var name in module.settings)143          if (module.settings.hasOwnProperty(name))144            Express.settings[module.name][name] = module.settings[name]145      }146            147      if ('utilities' in module)148        for (var name in module.utilities)149          if (module.utilities.hasOwnProperty(name))150            Express.utilities[name] = module.utilities[name]151      152      Express.modules.push(module)153    },154    155    /**156     * Start Express; binding to _host_ / _port_.157     *158     * @param {int} port159     * @param {string} host160     * @api public161     */162    163    start : function(port, host) {164      this.server.listen(port || 3000, host, this.server.callback)165    },166    167    server : {168      169      /**170       * Listen to _host_ / _port_ with _callback_.171       *172       * @param {int} port173       * @param {string} host174       * @param {function} callback175       * @api private176       */177      178      listen : function(port, host, callback) {179        node.http.createServer(callback).listen(port, host)180        puts('Express started at http://' + (host || '127.0.0.1') + ':' + port + '/')181      },182      183      /**184       * Request callback.185       *186       * @param  {object} request187       * @param  {object} response188       * @api private189       */190      191      callback : function(request, response){192        request.body = ''193        request.setBodyEncoding('utf8')194        request.addListener('body', function(chunk) { request.body += chunk })195        request.addListener('complete', function(){196          Express.home = Express.settings.basepath197          Express.response.body = null198          Express.response.status = 200199          Express.request = request200          request.headers = Express.arrayToHash(request.headers)201          request.uri.params = Express.parseNestedParams(request.uri.params)202          request.uri.path = Express.normalizePath(request.uri.path)203          Express.hook('onRequest')204          try { Express.response.body = Express.callRouteFor(request) }205          catch (e) { Express.fail(e) }206          Express.hook('onResponse')207          response.sendHeader(Express.response.status, Express.hashToArray(Express.response.headers))208          response.sendBody(Express.response.body || '')209          response.finish()210        })211      }212    },213    214    /**215     * Fail Express with exception _e_.216     *217     * @param  {object} e218     * @api private219     */220221    fail : function(e) {222      if (e.constructor == Express.Halt) return223      this.header('Content-Type', 'text/plain')224      this.response.body = e.message ? e.name + ': ' + e.message : e.toString()225      this.response.status = 500226    },227    228    /**229     * Return an associative array generated230     * from the key / value pairs in _hash_.231     *232     * @param  {hash} hash233     * @return {array}234     * @api public235     */236    237    hashToArray : function(hash) {238      var array = []239      for (var key in hash)240        if (hash.hasOwnProperty(key))241          array.push([key, hash[key]])242      return array243    },244    245    /**246     * Return hash generated from an247     * associative array.248     *249     * @param  {array} array250     * @return {hash}251     * @api public252     */253    254    arrayToHash : function(array) {255      var hash = {}256      for (i = 0, len = array.length; i < len; ++i)257        hash[array[i][0].toLowerCase()] = array[i][1]258      return hash259    },260    261    /**262     * JSON encode _object_263     *264     * @param  {mixed} object265     * @return {string}266     * @api public267     */268    269    jsonEncode : function(object) {270      return JSON.stringify(object)271    },272    273    /**274     * JSON decode _string_.275     *276     * @param  {string} string277     * @return {mixed}278     * @api public279     */280     281     jsonDecode : function(string) {282       return JSON.parse(string)283     },284     285    /**286     * Redirect to _url_.287     *288     * @param  {string} url289     * @api public290     */291    292    redirect : function(url) {293      this.header('Location', url)294      this.respond("Page or file has moved to `" + url + "'", 'Moved Temporarily')295    },296    297    /**298     * Set response status to _value_. Where value may be299     * a case-insensitive string such as 'Not Found', 'forbidden',300     * or a numeric HTTP response status code.301     *302     * @param  {int, string} value303     * @return {int}304     * @api public305     */306    307    status : function(value) {308      if (value == undefined) return309      if (typeof value == 'number') return this.response.status = value310      for (var code in node.http.STATUS_CODES)311        if (node.http.STATUS_CODES.hasOwnProperty(code))312          if (node.http.STATUS_CODES[code].toLowerCase() == value.toLowerCase())313            return this.response.status = parseInt(code)314    },315    316    /**317     * Set response _status_ and _body_.318     *319     * @param  {string} body320     * @param  {string, int} status321     * @api public322     */323    324    respond : function(body, status) {325      this.response.body = body326      this.status(status)327      throw new Express.Halt()328    },329    330    /**331     * Get or set response _name_ header.332     *333     * @param  {string} name334     * @param  {string} value335     * @return {string}336     * @api public337     */338    339    header : function(name, value) {340      return value ? 341        this.response.headers[name.toLowerCase()] = value :342          this.response.headers[name.toLowerCase()]343    },344    345    /**346     * Get request header _name_ optionally providing _default_347     * when _name_ is not present.348     *349     * @param  {string} name350     * @param  {string} default351     * @return {string}352     * @api public353     */354    355    requestHeader : function(name, defaultValue) {356      return this.request.headers[name.toLowerCase()] || defaultValue357    },358        359    /**360     * Return param _key_'s value or _defaultValue_ when361     * the param has not been set.362     *363     * @param  {string} key364     * @param  {mixed} defaultValue365     * @return {mixed}366     * @api public367     */368    369    param : function(key, defaultValue) {370      return this.request.uri.params[key] || defaultValue371    },372    373    /**374     * Parse params _string_ into a nested hash.375     *376     * @param  {string} string377     * @return {hash}378     * @api public379     */380    381    parseParams : function(string) {382      var params = {}, pairs = string.split('&'), pair383      for (i = 0, len = pairs.length; i < len; ++i) {384        pair = pairs[i].split('=')385        params[pair[0]] = pair[1]386      }387      return this.parseNestedParams(params)388    },389    390    /**391     * Parse _params_, splitting { user[info][name] : 'tj' } into392     * { user : { info : { name : 'tj' }}}393     *394     * @param  {hash} params395     * @return {hash}396     * @api public397     */398    399    parseNestedParams : function(params) {400      for (var key in params)401        if (params.hasOwnProperty(key))402          if (parts = key.split('['))403            if (parts.length > 1)404              for (i = 0, prop = params, len = parts.length; i < len; ++i) {405                var name = parts[i].replace(']', '')406                if (i == len - 1) {407                  prop[name] = params[key]408                  prop = params, delete params[key]409                }410                else {411                  prop = prop[name] = prop[name] || {}412                }413              }414                415      return params416    },417    418    /**419     * Parse _cookie_ string into an object (hash).420     *421     * @param  {string} cookie422     * @return {hash}423     * @api public424     */425    426    parseCookie : function(cookie) {427      var hash = {}428      if (!cookie) return hash429      var attrs = cookie.split(/\s*;\s*/)430      for (i = 0; i < attrs.length; ++i)431        hash[attrs[i].split('=')[0]] = unescape(attrs[i].split('=')[1])432      return hash433    },434    435    /**436     * Normalize a path. Strips trailing / leading whitespace437     * and slashes ('/').438     *439     * @param  {string} path440     * @return {string}441     * @api public442     */443    444    normalizePath : function(path) {445      if (typeof path != 'string') return path446      return path.replace(/^(\s|\/)*|(\s|\/)*$/g, '')447    },448    449    /**450     * Normalize _path_. When a RegExp it is simply returned,451     * otherwise a string is converted to a regular expression452     * surrounded by ^$. So /user/:id/edit would become:453     *454     * \^/user/(.*?)\/edit\$/455     *456     * Each param key (:id) will be captured and placed in the457     * params array, so param('id') would give the string captured.458     *459     * @param  {string} path460     * @return {regexp}461     * @api public462     */463    464    pathToRegexp : function(path) {465      Express.regexpKeys = []466      if (path.constructor == RegExp) return path467      path = path.replace(/:(\w+)/g, function(_, key){468        Express.regexpKeys.push(key)469        return '(.*?)'470      })471      return new RegExp('^' + this.escapeRegexp(path, '/ [ ]') + '$', 'i')472    },473    474    /**475     * Escape RegExp _chars_ in _string_. Where _chars_ 476     * defaults to regular expression special characters.477     *478     * _chars_ should be a space delimited list of characters,479     * for example '[ ] ( )'.480     *481     * @param  {string} string482     * @param  {string} chars483     * @return {Type}484     * @api public485     */486    487    escapeRegexp : function(string, chars) {488      var specials = (chars || '/ . * + ? | ( ) [ ] { } \\').split(' ').join('|\\')489      return string.replace(new RegExp('(\\' + specials + ')', 'g'), '\\$1')490    },491    492    /**493     * Return the contents of a function body.494     *495     * @param  {function} body496     * @return {string}497     * @api public498     */499    500    contentsOf : function(body) {501      if (typeof body != 'function') throw "Express.contentsOf(): `" + body + "' is not a function"502      return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]503    },504    505    /**506     * Eval _string_ in context of Express.507     *508     * @param  {string} string509     * @return {mixed}510     * @api public511     */512    513    eval : function(string) {514      return eval('with (Express){ with (Express.utilities){ ' + string + '}}')515    },516        517    /**518     * Escape special characters in _html_.519     *520     * @param  {string} html521     * @return {string}522     * @api public523     */524    525    escape : function(html) {526      return html.527        replace(/&/g, '&amp;').528        replace(/"/g, '&quot;').529        replace(/</g, '&lt;').530        replace(/>/g, '&gt;')531    },532    533    /**534     * Convert native arguments object into an535     * array with optional _offset_.536     *537     * @param  {arguments} args538     * @param  {int} offset539     * @return {array}540     * @api public541     */542    543    argsArray : function(args, offset) {544      return Array.prototype.slice.call(args, offset)545    },546    547    /**548     * Check if _route_ matches provides the proper549     * encoding types listed in _request_'s Accept header.550     *551     * @param  {hash} route552     * @param  {hash} request553     * @return {bool}554     * @api private555     */556    557    routeProvides : function(route, request) {558      if (!route.options.provides) return true559      if (route.options.provides.constructor != Array) 560        route.options.provides = [route.options.provides]561      for (i = 0, len = route.options.provides.length; i < len; ++i)562        if (request.headers.accept && request.headers.accept.match(route.options.provides[i]))563          return true564      return false565    },566    567    /**568     * Attept to match and call a route for 569     * the given _request_, returning the data570     * returned by the route callback.571     *572     * @param  {object} request573     * @return {mixed}574     * @api private575     */576    577    callRouteFor : function(request) {578      var route = this.findRouteFor(request) || this.settings.defaultRoute579      if (route.keys)580        for (i = 0, len = route.keys.length; i < len; ++i) 581          this.request.uri.params[route.keys[i]] = Express.captures[i+1] || null582      var body = this.eval(Express.contentsOf(route.callback))583      if (typeof body != 'string') 584        throw "route `" + route.method.toUpperCase() + ' ' + route.path + "' must return a string"585      return body586    },587    588    /**589     * Attemp to find and return a route matching _request_.590     *591     * @param  {object} request592     * @return {object}593     * @api private594     */595    596    findRouteFor : function(request) {597      for (i = 0, len = this.routes.length; i < len; ++i)598        if (this.routeMatches(this.routes[i], request))599          return this.routes[i]600    },601    602    /**603     * Check if _route_ matches _request_604     *605     * @param  {object} route606     * @param  {object} request607     * @return {bool}608     * @api private609     */610    611    routeMatches : function(route, request) {612      if (request.method.toLowerCase() != route.method) return false613      switch (route.path.constructor) {614        case String: return route.path == request.uri.path615        case RegExp: return !! (Express.captures = request.uri.path.match(route.path))616      }617    },618    619    /**620     * Return a routing function for _method_.621     *622     * @param  {string} method623     * @return {function}624     * @api private625     */626    627    routeFunctionFor : function(method) {628      return function(path, options, callback) {629        if (options.constructor == Function) callback = options, options = {}630        path = Express.pathToRegexp(Express.normalizePath(path))631        Express.routes.push({632          keys : Express.regexpKeys,633          path : path,634          method : method,635          options : options,636          callback : callback637        })638      }639    }640  }641  642  // --- Expose643  644  get = Express.routeFunctionFor('get')645  post = Express.routeFunctionFor('post')646  del = Express.routeFunctionFor('delete')647  put = Express.routeFunctionFor('put')648  use = Express.addModule649650  // --- Core Modules651  652  use(Express.BodyDecoder)653  use(Express.FauxMethod)654  use(Express.ContentLength)655  use(Express.DefaultContentType)656  use(Express.RedirectHelpers)657    658})()659660get('user', function(){661  'Foo'662})663664put('user', function(){665  p('PUT')666})667668del('user', function(){669  p('DELETE')670})671672// Express.start()