I am using Node.js and Expressjs for my server side coding and MongoDB as back end. I am new to all these technologies. I need to do a list of actions based on the request.
For example in user management
- Check the user already registered
- If registered resend the activation email
- If not registered then get the userId from another table that will maintain the ids for user,assets etc..[ I know MongoDB provide unique _id; but I need to have a unique integer id as userId ]
- Create the user
- Send the success or failure response.
To implement this i wrote the following code :
exports.register = function(req,res,state,_this,callback) {
switch(state) {
case 1: //check user already registered or not
_this.checkUser(req, res, ( state + 1 ), _this, _this.register, callback);
break;
case 2: //Already registered user so resend the activation email
_this.resendEmail(req, res, 200, _this, _this.register, callback);
break;
case 3: //not registered user so get the userId from another table that will maintain the ids for user,assets etc
_this.getSysIds(req, res, ( state + 2 ), _this, _this.register, callback);
break;
case 4: //create the entry in user table
_this.createUser(req, res, ( state + 1 ), _this, _this.register, callback);
break;
case 200: //Create Success Response
callback(true);
break;
case 101://Error
callback(false);
break;
default:
callback(false);
break;
}
};
The check user code is something like this
exports.checkUser = function(req,res,state,_this,next,callback) {
//check user already registered or not
if(user) {//Already registered user so resend the activation email
next(req,res,state,_this,callback);
}
else {//not registered user so get the userId
next(req,res,(state + 1),_this,callback);
}
}
And similarly the other functions.
The first call to the register function will do from the app.get as
user.register(req,res,1,this,function(status) {
//do somthing
});
Is there any better way to do this? The problem I am facing is based on some condition I have to follow a sequence of action. I can write all these in a nested callback structure but in that case I cannot reuse my code.
One of the problem that my boss told me was that in the code I am calling the function register and put it in a stack of callbacks as
state 1: chekuser
state 3: getIds
state 4: create user
And finally in state 200 and here i am just exiting from the stack? It may cause a stack overflow!
Is there any better way to handle the callbacks in Node.js/Expressjs ??
NOTE: The above is a sample code.I have many different situations like this.