-
-
Save datatypevoid/55dffe081e0080e8ddcf05199cd23f49 to your computer and use it in GitHub Desktop.
Separation of logic from request handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // mylogic.js | |
| var MyLogic = { | |
| _currentAccount: null, | |
| fetchAccountByID: function(id) { | |
| // fetch account from database, use promises to reject/resolve | |
| }, | |
| setCurrentAccount: function(account) { | |
| MyLogic._currentAccount = account; | |
| } | |
| getCurrentAccount: function(account) { | |
| return MyLogic._currentAccount; | |
| } | |
| viewAccount: function(account) | |
| account = account || MyLogic.getCurrentAccount(); | |
| return Promise.resolve() | |
| .then(function() { | |
| if (!account) { | |
| throw new Error('No account found'); | |
| } | |
| return { | |
| account: account, | |
| users: ['test user 1'] | |
| }; | |
| }); | |
| } | |
| }; | |
| module.exports = MyLogic; | |
| // MyController.js | |
| var myLogic = require('./mylogic'); | |
| module.exports = { | |
| paramID: function(req, res, next) { | |
| mylogic.fetchAccountById(req.param.accountID) | |
| .then(function(account) { | |
| myLogic.setCurrentAccount(account); | |
| next(); | |
| }) | |
| .catch(function(err) { | |
| next(err); | |
| }).done(); | |
| }, | |
| view: function(req, res, next) { | |
| myLogic.viewAccount(myLogic.getCurentAccount()) | |
| .then(viewmodel) { | |
| res.render('account', viewmodel); | |
| }) | |
| .catch(function(err) { | |
| res.render('account/error', { | |
| error: err.message | |
| }); | |
| }).done(); | |
| } | |
| } | |
| // routes.js | |
| app.param('accountID', mycontroller.paramID); | |
| app.get('/accounts/:accountID', mycontroller.view); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment