Skip to content

Instantly share code, notes, and snippets.

@lingo
Last active May 9, 2022 21:19
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lingo/5e53d2cb5b282d53d912 to your computer and use it in GitHub Desktop.
Save lingo/5e53d2cb5b282d53d912 to your computer and use it in GitHub Desktop.
Separation of logic from request handlers
// 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);
@lingo
Copy link
Author

lingo commented Aug 3, 2014

This is untested!

@avishaan
Copy link

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.

@lingo
Copy link
Author

lingo commented Dec 9, 2014

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