Only build a sl remoting handler when a model is added to the app.

This commit is contained in:
Ritchie Martori 2013-07-01 10:41:52 -07:00
parent 044d2c4bcc
commit a4fb3012bf
2 changed files with 35 additions and 31 deletions

View File

@ -60,12 +60,20 @@ app._models = [];
*/ */
app.model = function (Model) { app.model = function (Model) {
var remotes = this.remotes();
this._models.push(Model); this._models.push(Model);
Model.shared = true; Model.shared = true;
Model.app = this; Model.app = this;
if(Model._remoteHooks) { if(Model._remoteHooks) {
Model._remoteHooks.emit('attached', app); Model._remoteHooks.emit('attached', app);
} }
// add to the remote exports
remotes.exports[Model.pluralModelName] = Model;
// clear the handlers cache
this._handlers = {};
} }
/** /**
@ -76,25 +84,6 @@ app.models = function () {
return this._models; return this._models;
} }
/**
* Get all remote objects.
*/
app.remoteObjects = function () {
var result = {};
var models = this.models();
// add in models
models.forEach(function (ModelCtor) {
// only add shared models
if(ModelCtor.shared && typeof ModelCtor.sharedCtor === 'function') {
result[ModelCtor.pluralModelName] = ModelCtor;
}
});
return result;
}
/** /**
* Get the apps set of remote objects. * Get the apps set of remote objects.
*/ */
@ -102,3 +91,27 @@ app.remoteObjects = function () {
app.remotes = function () { app.remotes = function () {
return this._remotes || (this._remotes = RemoteObjects.create()); return this._remotes || (this._remotes = RemoteObjects.create());
} }
/**
* Get a remotes handler.
*/
app.handler = function (type) {
var handler = this._handlers[type];
if(!handler) {
// get the sl remoting object
var remotes = this.remotes();
// create and save the handler
handler = this._handlers[type] = remotes.handler(type);
}
return handler;
}
/*!
* Handlers
*/
app._handlers = {};

View File

@ -17,21 +17,12 @@ module.exports = rest;
function rest() { function rest() {
return function (req, res, next) { return function (req, res, next) {
var app = req.app; var handler = req.app.handler('rest');
var remotes = app.remotes();
// get all remote objects
var objs = app.remoteObjects();
// export remote objects
remotes.exports = objs;
var handler = remotes.handler('rest');
if(req.url === '/routes') { if(req.url === '/routes') {
res.send(handler.adapter.allRoutes()); res.send(handler.adapter.allRoutes());
} else if(req.url === '/models') { } else if(req.url === '/models') {
return res.send(remotes.toJSON()); return res.send(req.app.remotes().toJSON());
} else { } else {
handler(req, res, next); handler(req, res, next);
} }