Last active
May 9, 2022 21:19
-
-
Save lingo/5e53d2cb5b282d53d912 to your computer and use it in GitHub Desktop.
Separation of logic from request handlers
This file contains 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); |
I am frantically debating whether to separate thing out like this so that the modules can be required and directly tested vs just testing it via the api/interface.
Either way, you are putting wayyyyy too many spaces in your gist. Like I mean just way way way way too many.
I've been finding this an effective technique.
As for the spaces, it looks like I had the editor on "Indent mode: 2 Tabs" for some reason.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is untested!