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) {
var remotes = this.remotes();
this._models.push(Model);
Model.shared = true;
Model.app = this;
if(Model._remoteHooks) {
Model._remoteHooks.emit('attached', app);
}
// add to the remote exports
remotes.exports[Model.pluralModelName] = Model;
// clear the handlers cache
this._handlers = {};
}
/**
@ -76,29 +84,34 @@ app.models = function () {
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.
*/
app.remotes = function () {
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() {
return function (req, res, next) {
var app = req.app;
var remotes = app.remotes();
// get all remote objects
var objs = app.remoteObjects();
// export remote objects
remotes.exports = objs;
var handler = remotes.handler('rest');
var handler = req.app.handler('rest');
if(req.url === '/routes') {
res.send(handler.adapter.allRoutes());
} else if(req.url === '/models') {
return res.send(remotes.toJSON());
return res.send(req.app.remotes().toJSON());
} else {
handler(req, res, next);
}