This code is Express NodeJS code that handles post registration .post
action where the user must select a custom username. The username is validated, and if valid, the database is updated. If not, the user is redirected to the page with an error message so he/she can try again.
I would like to know if you would refactor this code with the extract method, that is extracting some functionality into their own extracted method to improve fragmentation of this code and readability.
// This route is only used for newly registered facebook user so they can supply a custom userName.
users_router.route( "/userName" )
// Process the customUserName recording.
.post( function( req, res ) {
// Receive data from the customUserName form field.
let form = new forms.IncomingForm()
form.parse( req, function( err, fields, files ) {
let userModel = new User( fields ).userModel() // Instantiate current user
let validationResults = new Validation( userModel, fields ).validationResults()
// There is no error: Update the customUserName field in the database.
if ( validationResults === g.error.no ) {
let properties: string = req.session[ "userModel" ].id.content // Session holds copy of model
let customUserNameField = fields[ "custom_user_name" ]
let customUserNameData = { "facebookId": properties, "customUserName": customUserNameField }
customUserNameDbUpdate( customUserNameData, function() {
console.log( "Custom user name was added" )
res.end( "ok" ) // TODO: redirect
})
}
// There are errors: redirect back to user name selection page with error message.
if ( validationResults !== g.error.no ) {
let errorMessage = validationResults[ "custom_user_name" ].errorMessage
res.render( "apps/users/views/chooseUsername.handlebars", { // TODO: should not redirect to template
error: errorMessage
})
}
})
})