Skip to content

Instantly share code, notes, and snippets.

@neilk
Last active August 29, 2015 13:56
Show Gist options
  • Save neilk/8949874 to your computer and use it in GitHub Desktop.
Save neilk/8949874 to your computer and use it in GitHub Desktop.
var db = Knex({ /* connection properties */ });
function sessionToAccount(session) {
return db('accounts').where('user_ID', session.user_ID).select();
}
function withdraw(account, amount) {
if (account.balance < amount) {
throw new Error("insufficient funds");
}
return db.raw('withdrawal(?,?)', account.ID, amount)
.then(function(result) {
return db('accounts').where('account', account.ID).select('balance')
.then(function(account) {
return({balance: account.balance, withdrawn: amount});
});
});
}
function getSession(session_id) {
return db('sessions').where('session_id', session_id).select();
}
function handleWithdrawal(req, res) {
getSession(req.param.session_id)
.then(sessionToAccount)
.then(function(account) {
withdraw(account, req.param.amount);
})
.then(res.end)
.catch(function(e) {
res.send(500, "Withdrawal error: " + e);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment