Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created June 11, 2022 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navanathjadhav/a1f93d923b2ba881b8b4e45e35f7c61a to your computer and use it in GitHub Desktop.
Save navanathjadhav/a1f93d923b2ba881b8b4e45e35f7c61a to your computer and use it in GitHub Desktop.
Code split into multiple functions
/**
* This method will verify user credentials and return adequate response
* @param userName username or email of user
* @param password password of the user
*/
function login(userName, password) {
/*
* Validate user credentials, moved to separate function
*/
validateCredentials(userName, password);
/*
* DB Operation: Query the user by his credentials
*/
const user = UserSchema.find({ email: userName, password: password });
/*
* Validation: user not found, invalid credentials
*/
if (!user) {
throw new Error(`Invalid credentials`);
}
/*
* Validate user status, moved to separate function
*/
return validateStatus(user);
}
/**
* This method will validate username & password
* @param userName username or email of user
* @param password password of the user
*/
function validateCredentials(userName, password) {
/*
* Validation: Check if username is not supplied
*/
if (!userName) {
throw new Error(`No username`);
}
/*
* Validation: Check if password is not supplied
*/
if (!password) {
throw new Error(`No password`);
}
}
/**
* This method will validate user's status
* @param user user data
*/
function validateStatus(user) {
let response = {};
/*
* User status check: return response as per user status
*/
switch (user.status) {
//////////////////////////////
// Active //
//////////////////////////////
case "Active":
response = { message: "Login successful", user: user };
break;
//////////////////////////////
// Inactive //
//////////////////////////////
case "Inactive":
response = { message: "User is inactive", user: undefined };
break;
//////////////////////////////
// Invited //
//////////////////////////////
case "Invited":
response = { message: "User is not activated yet", user: undefined };
break;
//////////////////////////////
// Blocked //
//////////////////////////////
case "Blocked":
response = { message: "User is blocked", user: undefined };
break;
//////////////////////////////
// Invalid Status //
//////////////////////////////
default:
response = { message: "User with invalid status", user: undefined };
break;
}
/*
* Return response
*/
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment