loopback/node_modules/resource/lib/resource.js

83 lines
1.8 KiB
JavaScript
Raw Normal View History

2013-04-09 18:33:29 +00:00
/**
* Expose `Resource`.
*/
module.exports = Resource;
/**
* Module dependencies.
*/
var asteroid = require('asteroid')
, AsteroidModule = require('asteroid-module')
, HttpContext = require('./http-context')
2013-04-09 18:33:29 +00:00
, 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;
2013-04-09 18:33:29 +00:00
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);
2013-04-09 18:33:29 +00:00
}