Skip to content

Instantly share code, notes, and snippets.

@bookercodes
Created September 1, 2015 20:48
Show Gist options
  • Save bookercodes/3acb5a75ad6555a2da81 to your computer and use it in GitHub Desktop.
Save bookercodes/3acb5a75ad6555a2da81 to your computer and use it in GitHub Desktop.
function redirectToScreencast(req, res) {
// alias the params so they are more terse to reference
var screencastId = req.params.screencastId;
var remoteAddress = req.connection.remoteAddress;
var sql = squel.select()
.from('screencasts')
.where('screencastId = ?', screencastId)
.toString();
connection.queryAsync(sql).spread(function(screencasts) {
var screencast = screencasts.shift();
if (!screencast) {
return res.status(404).send({error: 'sd'});
}
res.redirect(screencast.link);
var sql = squel.select()
.field('screencastId')
.from('referrals')
.where('screencastId = ? AND refereeRemoteAddress = ?', screencastId, remoteAddress)
.toString();
connection.queryAsync(sql).spread(function(referrals) {
var alreadyCounted = referrals.length > 0;
if (alreadyCounted) {
// this user's view has already been counted - do not count it again!
return;
}
connection.beginTransactionAsync().then(function() {
var sql = squel.update()
.table('screencasts')
.set('referralCount = referralCount + 1')
.where('screencastId = ?', screencastId)
.toString();
return connection.queryAsync(sql);
}).then(function() {
var sql = squel.insert()
.into('referrals')
.set('screencastId', screencastId)
.set('refereeRemoteAddress', remoteAddress)
.toString();
return connection.queryAsync(sql);
}).then(function() {
return connection.commit();
}).error(function() {
return connection.rollback();
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment