Last active
August 29, 2015 13:56
-
-
Save neilk/8949874 to your computer and use it in GitHub Desktop.
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
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