/** * Expose `Resource`. */ module.exports = Resource; /** * 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 `Resource` with the given `options`. * * @param {Object} options * @return {Resource} */ function Resource(options) { AsteroidModule.apply(this, arguments); // throw an error if args are not supplied assert(typeof options === 'object', 'Resource requires an options object'); assert(options.path, 'Resource 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(Resource, AsteroidModule); /** * Mount the sub app on the given parent app at the configured path. */ Resource.prototype.mount = function (parent) { this.parent = parent; parent.use(this.options.path, this.app); } /** * Create an http context bound to the current resource. */ Resource.prototype.createContext = function (req, res, next) { return new HttpContext(this, req, res, next); } /** * Override `on` to determine how many arguments an event handler expects. */ Resource.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); }