Created
March 24, 2014 18:34
-
-
Save qcom/9746304 to your computer and use it in GitHub Desktop.
my attempt at an expressjs route
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
/* relevant section of my db module */ | |
db.user = {}; | |
db.user.available = function(email) { | |
return knex('users') | |
.where('email', email) | |
.then(areNone); | |
}; | |
db.user.add = function(data) { | |
return knex('users') | |
.insert({ | |
first_name : data.firstName, | |
last_name : data.lastName, | |
identity : data.identity, | |
email : data.email, | |
salt : data.salt, | |
password : data.password | |
}, 'user_id') | |
.then(getFirst); | |
}; | |
db.company.add = function(data) { | |
return knex('companies') | |
.insert({ | |
company_name : data.companyName, | |
company_description : data.companyDescription, | |
user_id : data.userId | |
}); | |
}; | |
app.set('db', db); | |
/* route definition */ | |
app.route('/register') | |
.all(restrict) | |
.get(function(req, res) { | |
res.render('register'); | |
}) | |
.post(function(req, res) { | |
trim(req.body); | |
/* valid[model].validate returns either null (no error) or a string error message */ | |
var errMessage = valid.user.validate(req.body); | |
if (errMessage) { | |
req.session.error = errMessage; | |
res.redirect('/register'); | |
} else { | |
app.get('db').user.available(req.body.email).then(function(isAvailable) { | |
if (isAvailable) { | |
req.body.salt = bcrypt.genSaltSync(); | |
req.body.password = bcrypt.hashSync(req.body.password, req.body.salt); | |
app.get('db').user.add(req.body).then(function(userId) { | |
req.body.userId = userId; | |
app.get('db').company.add(req.body).then(function() { | |
req.session.success = "Account registration success"; | |
res.redirect('/register'); | |
}); | |
}); | |
} else { | |
req.session.error = "Sorry, your email address has already been registered"; | |
res.redirect('/register'); | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment