From a4fb3012bf37f5d8f8e8476eb7c187bf91f8ae7e Mon Sep 17 00:00:00 2001 From: Ritchie Martori Date: Mon, 1 Jul 2013 10:41:52 -0700 Subject: [PATCH] Only build a sl remoting handler when a model is added to the app. --- lib/application.js | 53 ++++++++++++++++++++++++++---------------- lib/middleware/rest.js | 13 ++--------- 2 files changed, 35 insertions(+), 31 deletions(-) diff --git a/lib/application.js b/lib/application.js index 5094ae74..6f28fbbd 100644 --- a/lib/application.js +++ b/lib/application.js @@ -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()); -} \ No newline at end of file +} + +/** + * 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 = {}; \ No newline at end of file diff --git a/lib/middleware/rest.js b/lib/middleware/rest.js index a22dadcf..5830ed71 100644 --- a/lib/middleware/rest.js +++ b/lib/middleware/rest.js @@ -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); }