Created
September 24, 2015 16:50
-
-
Save beeekind/059772c8d5a383dd5e2b to your computer and use it in GitHub Desktop.
Example of a express JS helper function with multiple asynchronous actions that must be completed in a certain order
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
"use strict"; | |
/** @module CreateUser */ | |
var models = require("../wrapper").getSingleton(); | |
var async = require("async"); | |
var password = require("password-hash-and-salt"); | |
/** | |
* Create a user with a variable number of fields and a salted/hashed password, all users should | |
* be created through this interface. | |
* | |
* @param {object} params - object containing desired user parameters | |
* @param {string} [params.username] - optional string representing the user's username | |
* @param {string} [params.phone] - optional string representing the user's phone number | |
* @param {string} [params.email] - optional string representing the user's email address | |
* @param {string} params.password - string representing the user's password | |
* @param callback {function} - call back function that we return through asynchronously | |
*/ | |
module.exports = function(params, callback){ | |
// validate parameters, not exhaustive (like if username is Number) | |
if (!params.password || typeof params.password !== "string") { throw new Error("Invalid password parameter"); } | |
if (!callback || typeof callback !== "function") { throw new Error("Invalid callback parameter"); } | |
// params must include one of username, email, or phone, as a unique identifier for the user | |
if (!params.username && !params.email && !params.phone){ throw new Error("Must have one of username, email, phone"); } | |
// create a hashed password and then create a user with that password and given parameters | |
async.series({ | |
password: function(done){ | |
password(params.password).hash(function(error, hash) { | |
params.password = hash; | |
done(error, hash); | |
}); | |
}, | |
userInstance: function(done){ | |
models.User.create(params) | |
.then(function(userInstance){ | |
done(null, userInstance); | |
}) | |
.catch(function(err){ | |
done(err); | |
}); | |
} | |
}, callback); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment