/** * Expose `Route`. */ module.exports = Route; /** * Module dependencies. */ var asteroid = require('asteroid') , AsteroidModule = require('asteroid-module') , HttpContext = require('./http-context') , debug = require('debug')('asteroid:resource') , util = require('util') , inherits = util.inherits , assert = require('assert'); /** * Create a new `Route` with the given `options`. * * @param {Object} options * @return {Route} */ function Route(options) { AsteroidModule.apply(this, arguments); // throw an error if args are not supplied assert(typeof options === 'object', 'Route requires an options object'); assert(options.path, 'Route requires a path'); // create the sub app var app = this.app = asteroid(); this.options = options; debug('created with options', options); this.on('destroyed', function () { app.disuse(this.options.path); }); } /** * Inherit from `AsteroidModule`. */ inherits(Route, AsteroidModule); /** * Mount the sub app on the given parent app at the configured path. */ Route.prototype.mount = function (parent) { this.parent = parent; parent.use(this.options.path, this.app); } /** * Create an http context bound to the current resource. */ Route.prototype.createContext = function (req, res, next) { return new HttpContext(this, req, res, next); } /** * Override `on` to determine how many arguments an event handler expects. */ Route.prototype.on = function () { var fn = arguments[arguments.length - 1]; if(typeof fn === 'function') { // parse expected arguments from function src // fn.listener handles the wrapped function during `.once()` var src = (fn.listener || fn).toString(); fn._expects = src.split('{')[0].split(',').length; } AsteroidModule.prototype.on.apply(this, arguments); }