Best JavaScript code snippet using root
userController.js
Source:userController.js
...24 && !check.isEmpty(req.body.mobileNumber) && !check.isEmpty(req.body.password) 25 && !check.isEmpty(req.body.country) && !check.isEmpty(req.body.userType)26 && !check.isEmpty(req.body.userName)) {27 if (!validateInput.Email(req.body.email)) {28 let apiResponse = response.generateResponse(true, 'Email Does not meet the requirement', 400, null)29 reject(apiResponse)30 } else if (!validateInput.Password(req.body.password)) {31 let apiResponse = response.generateResponse(true, 'Password Does not meet the requirement', 400, null)32 reject(apiResponse)33 } else if (!validateInput.FirstName(req.body.firstName)) {34 let apiResponse = response.generateResponse(true, 'First Name Does not meet the requirement', 400, null)35 reject(apiResponse)36 }37 else if (!validateInput.LastName(req.body.lastName)) {38 let apiResponse = response.generateResponse(true, 'Last Name Does not meet the requirement', 400, null)39 reject(apiResponse)40 }41 else if (!validateInput.mobileNumber(req.body.mobileNumber)) {42 43 let apiResponse = response.generateResponse(true, 'Mobile Number Does not meet the requirement', 400, null)44 reject(apiResponse)45 }46 else if (!validateInput.userName(req.body.userName)) {47 48 let apiResponse = response.generateResponse(true, 'User Name Does not meet the requirement', 400, null)49 reject(apiResponse)50 }515253 else {54 console.log('yes')55 resolve(req)56 }57 } else {58 logger.error('Field Missing During User Creation', 'userController: createUser()', 5)59 let apiResponse = response.generateResponse(true, 'One or More Parameter(s) is missing', 400, null)60 reject(apiResponse)61 }62 })63 }// end validate user input6465 let createUser = () => {66 return new Promise((resolve, reject) => {67 let email = req.body.email.toLowerCase();68 UserModel.findOne({ email: email })69 .exec((err, retrievedUserDetails) => {70 if (err) {7172 logger.error(err.message, 'userController: createUser', 10)73 let apiResponse = response.generateResponse(true, 'Failed To Create User', 500, null)74 reject(apiResponse)75 } else if (check.isEmpty(retrievedUserDetails)) {767778 let newUser = new UserModel({79 userId: shortid.generate(),80 userType:req.body.userType,81 firstName: req.body.firstName,82 lastName: req.body.lastName || '',83 userName:req.body.userName,84 email: req.body.email.toLowerCase(),85 mobileNumber: req.body.mobileNumber,86 country: req.body.country,87 password: passwordLib.hashpassword(req.body.password),88 hash: req.hash89 })90 newUser.save((err, newUser) => {91 if (err) {92 console.log(err)93 logger.error(err.message, 'userController: createUser', 10)94 let apiResponse = response.generateResponse(true, 'Failed to create new User', 500, null)95 reject(apiResponse)96 } else {97 let newUserObj = newUser.toObject();98 resolve(newUserObj)99 }100 })101 } else {102 console.log(retrievedUserDetails);103 logger.error('User Cannot Be Created.User Already Present', 'userController: createUser', 4)104 let apiResponse = response.generateResponse(true, 'User Already Present With this Email', 403, null)105 reject(apiResponse)106 }107 })108 })109 }// end create user function110111 let sendMail = (newUserObj) => {112 return new Promise((resolve, reject) => {113 let data={114 "email":req.body.email,115 "hash":req.hash,116 "name":`${req.body.firstName} ${req.body.lastName}`117 };118 var transporter = nodemailer.createTransport({119 service: 'Gmail',120 auth: {121 user: 'saknigam12@gmail.com',122 pass: 'sakanchal1295@'123 }124 });125126 const mailOptions = {127 from: 'saknigam12@email.com', // sender address128 to: data.email, // list of receivers129 subject: 'Please confirm your Email account', // Subject line130 text: `Hi! ${data.name},131 Please Click on the link to verify your email.`,// plain text body132 html:'<a href="http://meetingtime.webdeveloperjourney.xyz/verify/'+data.hash+'">http://localhost:4200/'+data.hash+'</a>'133 };134 console.log(mailOptions)135 transporter.sendMail(mailOptions, function (err, info) {136 137 if (err) {138 console.log(err);139 logger.error('Sent Mail Failed!', 'User Controller: createUser', 10)140 let apiResponse = response.generateResponse(true, 'Server Error!Sent Mail Failed.', 500, null)141 reject(apiResponse)142143144 }145 else {146 console.log(info);147 logger.error('Mail Sent Successful!', 'User Controller: createUser', 10)148149 resolve(newUserObj)150 }151 });152153154 });155156 }//end157158 validateUserInput()159 .then(createUser)160 .then(sendMail)161 .then((resolve) => {162 delete resolve.password163 let apiResponse = response.generateResponse(false, 'User created and Mail sent Successful!', 200, resolve)164 res.send(apiResponse)165166 })167 .catch((err) => {168 res.send(err)169170 })171172173}//end174175//verify email function176let verifyEmail=(req,res)=>{177 if (check.isEmpty(req.body.hash)) {178179 console.log('Hash should be passed')180 let apiResponse = response.generateResponse(true, 'Hash is missing', 403, null)181 res.send(apiResponse)182 }183 else{184 let hash = { $set: { active: true } };;185 UserModel.update({ 'hash': req.body.hash },hash, { multi: true })186 .exec((err, result) => {187 if (err) {188189 console.log('Error Occured.')190 logger.error(`Error Occured : ${err}`, 'Database', 10)191 let apiResponse = response.generateResponse(true, 'Error Occured.', 500, null)192 res.send(apiResponse)193 } else if (check.isEmpty(result)) {194195 console.log('User Not Found.')196 logger.error('User Not Found', 'userController: verifyEmail', 10)197 let apiResponse = response.generateResponse(true, 'User Not found', 404, null)198 res.send(apiResponse)199 } else {200 console.log('User Verified Successfully')201 logger.error('User Verified Successfully!', 'userController: verifyEmail', 10)202 let apiResponse = response.generateResponse(false, 'User Verified Successfully.', 200, result)203 res.send(apiResponse)204 }205206 });207208 }209}210//end verify email211212// start of login function 213let loginFunction = (req, res) => {214 let findUser = () => {215 console.log("findUser");216 return new Promise((resolve, reject) => {217 if (req.body.email && req.body.userType) {218 console.log("req body email is there");219 220 let email=req.body.email.toLowerCase();221 let userType=req.body.userType;222 UserModel.findOne({ email: email,userType:userType})223 .exec((err, userDetails) => {224 /* handle the error here if the User is not found */225 if (err) {226 console.log(err)227 logger.error('Failed To Retrieve User Data', 'userController: findUser()', 10)228 229 let apiResponse = response.generateResponse(true, 'Failed To Find User Details', 500, null)230 reject(apiResponse)231 232 } else if (check.isEmpty(userDetails)) {233 /* generate the response and the console error message here */234 logger.error('No User Found', 'userController: findUser()', 7)235 let apiResponse = response.generateResponse(true, 'No User Details Found', 404, null)236 reject(apiResponse)237 } else {238 /* prepare the message and the api response here */239 logger.info('User Found', 'userController: findUser()', 10)240 resolve(userDetails)241 }242 });243 244 } else {245 let apiResponse = response.generateResponse(true, 'parameters are missing', 400, null)246 reject(apiResponse)247 }248 });249 } //find user end250251 let validatePassword = (retrievedUserDetails) => {252 console.log("validatePassword");253 return new Promise((resolve, reject) => {254 if (req.body.password) {255 passwordLib.comparePassword(req.body.password, retrievedUserDetails.password, (err, isMatch) => {256 257 if (err) {258 console.log(err)259 logger.error(err.message, 'userController: validatePassword()', 10)260 let apiResponse = response.generateResponse(true, 'Login Failed', 500, null)261 reject(apiResponse)262 } else if (isMatch) {263 let retrievedUserDetailsObj = retrievedUserDetails.toObject()264 265 console.log(retrievedUserDetailsObj);266 delete retrievedUserDetailsObj.password267 delete retrievedUserDetailsObj._id268 delete retrievedUserDetailsObj.__v269 delete retrievedUserDetailsObj.createdOn270 delete retrievedUserDetailsObj.hash271 272273 resolve(retrievedUserDetailsObj)274 } else {275 logger.info('Login Failed Due To Invalid Password', 'userController: validatePassword()', 10)276 let apiResponse = response.generateResponse(true, 'Wrong Password!Login Failed', 400, null)277 reject(apiResponse)278 }279 });280 }//end if statement281 else{282 let apiResponse = response.generateResponse(true, 'Password parameter is missing', 400, null)283 reject(apiResponse)284 }285 });286 } //end validate password287288 //METHOD TO CHECK whether the user verify himself by link provided in email289 let checkStatus=(retrievedUserDetails)=>{290 return new Promise((resolve, reject) => {291 if(retrievedUserDetails.active==false){292 let apiResponse = response.generateResponse(true, 'User has not Verified!', 400, null)293 reject(apiResponse);294 }295 else{296 delete retrievedUserDetails.active;297 resolve(retrievedUserDetails);298 }299300 });301 }//end 302303 let generateToken = (userDetails) => {304 console.log("generate token");305 return new Promise((resolve, reject) => {306 token.generateToken(userDetails, (err, tokenDetails) => {307 if (err) {308 console.log(err)309 let apiResponse = response.generateResponse(true, 'Failed To Generate Token', 500, null)310 reject(apiResponse)311 } else {312 tokenDetails.userId = userDetails.userId313 tokenDetails.userDetails = userDetails314 315 resolve(tokenDetails)316 }317 })318 })319 }//end generate token320321 let saveToken = (tokenDetails) => {322 console.log("save token");323 return new Promise((resolve, reject) => {324 AuthModel.findOne({ userId: tokenDetails.userId }, (err, retrievedTokenDetails) => {325 if (err) {326 console.log(err.message, 'userController: saveToken', 10)327 let apiResponse = response.generateResponse(true, 'Failed To Generate Token', 500, null)328 reject(apiResponse)329 } else if (check.isEmpty(retrievedTokenDetails)) {330 let newAuthToken = new AuthModel({331 userId: tokenDetails.userId,332 authToken: tokenDetails.token,333 tokenSecret: tokenDetails.tokenSecret,334 tokenGenerationTime: Date.now()335 })336 newAuthToken.save((err, newTokenDetails) => {337 if (err) {338 console.log(err)339 logger.error(err.message, 'userController: saveToken', 10)340 let apiResponse = response.generateResponse(true, 'Failed To Generate Token', 500, null)341 reject(apiResponse)342 } else {343 let responseBody = {344 authToken: newTokenDetails.authToken,345 userDetails: tokenDetails.userDetails346 }347 resolve(responseBody)348 }349 })350 } else {351 retrievedTokenDetails.authToken = tokenDetails.token352 retrievedTokenDetails.tokenSecret = tokenDetails.tokenSecret353 retrievedTokenDetails.tokenGenerationTime = Date.now()354 retrievedTokenDetails.save((err, newTokenDetails) => {355 if (err) {356 console.log(err)357 logger.error(err.message, 'userController: saveToken', 10)358 let apiResponse = response.generateResponse(true, 'Failed To Generate Token', 500, null)359 reject(apiResponse)360 } else {361 let responseBody = {362 authToken: newTokenDetails.authToken,363 userDetails: tokenDetails.userDetails364 }365 resolve(responseBody)366 }367 })368 }369 })370 })371 } //save token end372373 findUser()374 .then(validatePassword)375 .then(checkStatus)376 .then(generateToken)377 .then(saveToken)378 .then((resolve) => {379 let apiResponse = response.generateResponse(false, 'Login Successful', 200, resolve)380 res.status(200)381 res.send(apiResponse)382 })383 .catch((err) => {384 console.log("errorhandler");385 386 res.send(err)387 });388}//end of login funtion389 390//forgot password function391let forgotPassword=(req,res)=>{392 var transporter = nodemailer.createTransport({393 service: 'Gmail',394 auth: {395 user: 'saknigam12@gmail.com',396 pass: 'sakanchal1295@'397 }398 });399 400 let secretKey="mychoiceypassword";401 let emailEncrypt=btoa(req.body.email+secretKey);402 const mailOptions = {403 from: 'saknigam12@email.com', // sender address404 to: req.body.email, // list of receivers405 subject: 'Reset your password', // Subject line406 html: "<p>Hi!,<br/>Please <a href='http://meetingtime.webdeveloperjourney.xyz/reset/"+emailEncrypt+"'>Click here</a> to change your password!</p>"407 408 };409 console.log(mailOptions)410 transporter.sendMail(mailOptions, function (err, info) {411 if(err){412 console.log(err);413 logger.error('Sent Mail Failed!', 'User Controller: forgotPassword', 10)414 let apiResponse = response.generateResponse(true, 'Server Error!Sent Mail Failed.', 500, null)415 res.send(apiResponse)416417 418 }419 else{420 console.log(info);421 logger.error('Mail Sent Successful!', 'User Controller: forgotPassword', 10)422 let apiResponse = response.generateResponse(false, 'Mail Sent Successful!', 200, null)423 res.send(apiResponse)424 }425 });426427428}429//end forgotpassword430431432//reset passsword433let resetPassword=(req,res)=>{434 let emailCheck=()=>{435 return new Promise((resolve, reject) => {436 if (check.isEmpty(req.body.email) || (check.isEmpty(req.body.password))) {437438 console.log('Parameters should be passed')439 let apiResponse = response.generateResponse(true, 'One or more parameter is missing', 403, null)440 reject(apiResponse)441 }442 else{443 UserModel.findOne({ 'email': req.body.email })444 .exec((err,result)=>{445 if(err){446 console.log(err)447 logger.error(err.message, 'User Controller: resetPassword', 10)448 let apiResponse=response.generateResponse(true,"Error Occured!",500,null);449 reject(apiResponse)450 }451 else if (check.isEmpty(result)) {452 console.log('Email does not exist!')453 logger.info('Email does not exist!', 'user Controller: resetPssword',5)454 let apiResponse=response.generateResponse(true,"Email does not exist!",404,null);455 reject(apiResponse)456 457 }458 else{459 resolve(result);460 461 }462463464 });465 }//else statement466});467 }//emailcheck function 468 469let changePassword=(userDetails)=>{470 return new Promise((resolve, reject) => {471 userDetails.password=passwordLib.hashpassword(req.body.password);472 userDetails.save((error,resul)=>{473 if (error) {474 console.log(error)475 logger.error(err.message, 'User Controller: resetPassword', 10)476 let apiResponse=response.generateResponse(true,"Error Occured!",500,null);477 reject(apiResponse)478 }479 else {480 console.log("Password changed successfully")481 logger.info('Password changed Successfully!', 'User Controller: resetPssword',5)482 let apiResponse=response.generateResponse(false,"Password changed successfully!",200,resul);483 resolve(apiResponse)484485 }486 });487488 });489}//end change password490491emailCheck()492.then(changePassword)493.then((resolve) => {494 delete resolve.password495496 res.send(resolve)497})498.catch((err) => {499 console.log(err);500 res.send(err);501})502503504}//end reset password505506507/* Get all user Details */508let getAllUser = (req, res) => {509 UserModel.find()510 .select('-password -__v -_id -createdOn -active -hash')511 .lean()512 .exec((err, result) => {513 if (err) {514 console.log(err)515 logger.error(err.message, 'User Controller: getAllUser', 10)516 let apiResponse = response.generateResponse(true, 'Failed To Find User Details', 500, null)517 res.send(apiResponse)518 } else if (check.isEmpty(result)) {519 logger.info('No User Found', 'User Controller: getAllUser',5)520 let apiResponse = response.generateResponse(true, 'No User Found', 404, null)521 res.send(apiResponse)522 } else {523 let apiResponse = response.generateResponse(false, 'All User Details Found', 200, result)524 res.send(apiResponse)525 }526 })527528529}//end get all user function530531/* Get all normaluser Details */532let getAllNormalUser = (req, res) => {533 UserModel.find({userType:1})534 .select('-password -__v -_id -createdOn -active -hash')535 .lean()536 .exec((err, result) => {537 if (err) {538 console.log(err)539 logger.error(err.message, 'User Controller: getAllUser', 10)540 let apiResponse = response.generateResponse(true, 'Failed To Find User Details', 500, null)541 res.send(apiResponse)542 } else if (check.isEmpty(result)) {543 logger.info('No User Found', 'User Controller: getAllUser',5)544 let apiResponse = response.generateResponse(true, 'No User Found', 404, null)545 res.send(apiResponse)546 } else {547 let apiResponse = response.generateResponse(false, 'All User Details Found', 200, result)548 res.send(apiResponse)549 }550 })551552553}//end get all user function554555let editUser = (req, res) => {556 if (check.isEmpty(req.params.userId)) {557558 console.log('User Id should be passed')559 let apiResponse = response.generateResponse(true, 'User Id is missing', 403, null)560 res.send(apiResponse)561 }562 else {563 let options = req.body;564 UserModel.findOne({ 'userId': req.params.userId })565 .exec((err, result) => {566567 if (err) {568 console.log(err)569 logger.error(err.message, 'User Controller: editUser', 10)570 let apiResponse = response.generateResponse(true, "Error Occured!", 500, null);571 res.send(apiResponse)572 }573 else if (check.isEmpty(result)) {574 console.log('No user Found')575 logger.info('No user Found', 'user Controller: editUser', 5)576 let apiResponse = response.generateResponse(true, "No user Found!", 404, null);577 res.send(apiResponse)578579 }580 else {581 for (let i in options) {582 result[i] = options[i];583 }584 result.save((error, resul) => {585 if (error) {586 console.log(error)587 logger.error(err.message, 'User Controller: editUser', 10)588 let apiResponse = response.generateResponse(true, "Error Occured!", 500, null);589 res.send(apiResponse)590 }591 else {592 console.log("User Details updated successfully")593 logger.info('User Details Update Successfully!', 'User Controller: editUser', 5)594 let apiResponse = response.generateResponse(false, "User Details Updated successfully!", 200, resul);595 res.send(apiResponse)596597 }598 });599 }600601 });602 }603}//edit functionn end604605//Delete user606let deleteUser = (req, res) => {607 if (check.isEmpty(req.params.userId)) {608609 console.log('UserId should be passed')610 let apiResponse = response.generateResponse(true, 'userId is missing', 403, null)611 res.send(apiResponse)612 }613 else {614 UserModel.remove({ 'userId': req.params.userId })615 .exec((err, result) => {616 if (err) {617 console.log(err)618 logger.error(err.message, 'User Controller: deleteUser', 10)619 let apiResponse = response.generateResponse(true, 'Failed To delete user', 500, null)620 res.send(apiResponse)621 } else if (result.n == 0) {622 logger.info('No User Found', 'User Controller: deleteUser',10)623 let apiResponse = response.generateResponse(true, 'No User Found', 404, null)624 res.send(apiResponse)625 } else {626 let apiResponse = response.generateResponse(false, 'Deleted the user successfully', 200, null)627 res.send(apiResponse)628 }629 });// end user model find and remove630631 }632}//end delete function633634let logout = (req, res) => {635console.log(req.query.authToken);636 AuthModel.remove({authToken: req.query.authToken}, (err, result) => {637 if (err) {638 console.log(err)639 logger.error(err.message, 'user Controller: logout', 10)640 let apiResponse = response.generateResponse(true, `error occurred: ${err.message}`, 500, null)641 res.send(apiResponse)642 } else if (check.isEmpty(result)) {643 logger.info('empty', 'user Controller: logout', 10)644 let apiResponse = response.generateResponse(true, 'Already Logged Out or Invalid UserId', 404, null)645 res.send(apiResponse)646 } else {647 logger.info('no', 'user Controller: logout', 10)648 let apiResponse = response.generateResponse(false, 'Logged Out Successfully', 200, null)649 res.send(apiResponse)650 }651 })652 653} // end of the logout function.654655module.exports = {656 signUpFunction: signUpFunction,657 getAllUser: getAllUser,658 getAllNormalUser:getAllNormalUser,659 verifyEmail:verifyEmail,660 forgotPassword:forgotPassword,661 resetPassword:resetPassword,662 loginFunction:loginFunction,
...
users.js
Source:users.js
...10 var user = new User(params);11 user.save(function(err,user){12 console.log(user);13 if( !(_.isNull(err)) ){14 var response_string = genRes.generateResponse(false , "There occured some error : "+err.err);15 callback(response_string);16 }17 else{18 var response_string = genRes.generateResponse(true,"User created successfully");19 callback(response_string);20 }21 })22}23//the callback is returned with the response string and data24exports.login = function(params,callback){25 var email = params.email;26 var password = params.password;27 password = crypto.createHash('sha1').update(password).digest('hex');28 User.findOne({ 'email' : email, 'password' : password }, function(err,user){29 console.log(user);30 console.log(err);31 if( _.isNull(err) && !_.isNull(user) ){32 var session_obj = {33 'user_id' : user.id,34 'start_time' : Date()35 };36 UserTerm.add(session_obj,function(msg,session){37 var msg_obj = JSON.parse(msg);38 if( msg_obj.status ){39 var response_string = genRes.generateResponse(true,"user logged in successfully")40 callback(response_string,session);41 }42 else{43 var response = genRes.generateResponse(false,"There occured some error "+msg);44 callback(response,null);45 }46 });47 48 }49 else{50 var response_string = genRes.generateResponse(false,"no user found or there occured some error : "+err);51 callback(response_string,null);52 }53 })54};55// exports.login = function(email,password,callback){56// password = crypto.createHash('sha1').update(password).digest('hex');57// User.findOne({ 'email' : email, 'password' : password }, function(err,user){58// //console.log(user,err);59// if( _.isNull(err) && !_.isNull(user) ){60// var session_obj = {61// 'user_id' : user.id,62// 'start_time' : Date()63// };64// UserTerm.add(session_obj,function(msg,session){65// var msg_obj = JSON.parse(msg);66// if( msg_obj.status ){67// var response_string = genRes.generateResponse(true,"user logged in successfully")68// callback(response_string,session);69// }70// else{71// var response = genRes.generateResponse(false,"There occured some error "+msg);72// callback(response,null);73// }74// });75 76// }77// else{78// var response_string = genRes.generateResponse(false,"no user found or there occured some error : "+err);79// callback(response_string,null);80// }81// })82// };83exports.authenticateJabber = function(username,server,password,callback){84 password = crypto.createHash('sha1').update(password).digest('hex');85 var id = username;86 User.findOne({ '_id' : id, password : password },function(err,user){87 if( _.isNull(err) && !_.isNull(user) ){88 callback(true);89 }90 else{91 callback(false);92 }93 });94}95exports.showAll = function(callback){96 User.find(function(err,users){97 callback(users);98 });99}100//update password101exports.updatePassword = function(user_id,old_password,new_password,callback){102 var old_password = crypto.createHash('sha1').update(old_password).digest('hex');103 var new_password_hash = crypto.createHash('sha1').update(new_password).digest('hex');104 User.findById(user_id , function(err,user){105 if(err == null){106 var password = user.password;107 if( old_password === password ){108 User.update({ '_id' : user_id } ,{ 'password' : new_password_hash }, function(err,numberAffected, raw){109 if( err == null ){110 //console.log(numberAffected,raw);111 var response = genRes.generateResponse(true,"Updated password successfully");112 callback(response);113 }114 else{115 var response = genRes.generateResponse(false,"There occured some error "+err);116 callback(response);117 }118 });119 }120 else{121 var response = genRes.generateResponse(false,"Password provided do not match original password");122 callback(response);123 }124 }125 else{126 var response = genRes.generateResponse(false,"no user found");127 callback(response);128 }129 });130}131//reset password132exports.reset = function(email,callback){133 var new_password = 'zozo123';134 var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";135 var string_length = 8;136 var randomstring = '';137 for (var i=0; i<string_length; i++) {138 var rnum = Math.floor(Math.random() * chars.length);139 randomstring += chars.substring(rnum,rnum+1);140 }141 var new_password = randomstring;142 var new_password_hash = crypto.createHash('sha1').update(new_password).digest('hex');143 144 User.update({ 'email' : email } ,{ 'password' : new_password_hash }, function(err,numberAffected, raw){145 if( err == null ){146 //console.log(numberAffected,raw);147 var response = genRes.generateResponse(true,"Password reset successfull "+randomstring);148 callback(response);149 }150 else{151 var response = genRes.generateResponse(false,"There occured some error "+err);152 callback(response);153 }154 }); 155}156//update user details157exports.update = function(user_id,params,callback){158 User.findByIdAndUpdate(user_id,params,function(err,user){159 if( _.isNull(err) ){160 var response = genRes.generateResponse(true,"details updated successfully");161 callback(response);162 }163 else{164 var response = genRes.generateResponse(false,"there occured some error : "+err);165 callback(response);166 }167 })168}169exports.find = function(params,callback){170 User171 .find(params)172 .limit(5)173 .exec(function(err,users){174 //console.log(params);175 if( _.isNull(err) && users.length > 0 ){176 var response = genRes.generateResponse(true,"found successfully");177 callback(response,users);178 }179 else if( users.length == 0 ){180 var response = genRes.generateResponse(true,"No user found");181 callback(response,null);182 }183 else{184 var response = genRes.generateResponse(false,"there occured some error : "+err);185 callback(response,null);186 }187 })188}189exports.findbyid = function(user_id,callback){190 User.findById(user_id , function(err,user){ 191 if( _.isNull(err) ){192 var response = genRes.generateResponse(true,"found successfully");193 callback(response,user);194 } 195 else{196 var response = genRes.generateResponse(false,"there occured some error : "+err);197 callback(response,null);198 }199 })...
uses-text-compression-test.js
Source:uses-text-compression-test.js
...7const KB = 1024;8const ResponsesAreCompressedAudit =9 require('../../../audits/byte-efficiency/uses-text-compression.js');10const assert = require('assert');11function generateResponse(options) {12 return Object.assign({13 url: `http://google.com/${options.file}`,14 transferSize: options.resourceSize || 0,15 resourceSize: 0,16 gzipSize: 0,17 }, options);18}19/* eslint-env jest */20describe('Page uses optimized responses', () => {21 it('fails when responses are collectively unoptimized', () => {22 const auditResult = ResponsesAreCompressedAudit.audit_({23 ResponseCompression: [24 generateResponse({file: 'index.js', resourceSize: 100 * KB, gzipSize: 90 * KB}), // 10kb & 10%25 generateResponse({file: 'index.css', resourceSize: 50 * KB, gzipSize: 37 * KB}), // 13kb & 26% (hit)26 generateResponse({file: 'index.json', resourceSize: 2048 * KB, gzipSize: 1024 * KB}), // 1024kb & 50% (hit)27 ],28 });29 assert.equal(auditResult.items.length, 2);30 });31 it('passes when all responses are sufficiently optimized', () => {32 const auditResult = ResponsesAreCompressedAudit.audit_({33 ResponseCompression: [34 generateResponse({file: 'index.js', resourceSize: 1000 * KB, gzipSize: 910 * KB}), // 90kb & 9%35 generateResponse({file: 'index.css', resourceSize: 6 * KB, gzipSize: 4.5 * KB}), // 1,5kb & 25% (hit)36 generateResponse({file: 'index.json', resourceSize: 10 * KB, gzipSize: 10 * KB}), // 0kb & 0%37 generateResponse({file: 'compressed.json', resourceSize: 10 * KB, transferSize: 3 * KB,38 gzipSize: 6 * KB}), // 0kb & 0%39 ],40 });41 assert.equal(auditResult.items.length, 1);42 });...
Using AI Code Generation
1var rootController = require('./controllers/rootController');2var express = require('express');3var app = express();4app.get('/test', rootController.generateResponse);5app.listen(3000);6var rootController = {};7rootController.generateResponse = function(req, res) {8 res.send('test');9}10module.exports = rootController;
Using AI Code Generation
1var root = require('root');2var response = root.generateResponse();3var root = require('root');4var response = root.generateResponse();5module.exports.generateResponse = function(){6 return 'Hello World';7};8var root = require('root');9var response = root.generateResponse();10exports.generateResponse = function(){11 return 'Hello World';12};13var root = require('root');14var response = root.generateResponse();
Using AI Code Generation
1var rootController = require('./controllers/rootController');2var response = rootController.generateResponse('Hello World');3console.log(response);4var rootController = {5 generateResponse: function(message) {6 return {7 };8 }9};10module.exports = rootController;11exports.generateResponse = function(message) {12 return {13 };14};15module.exports = {16 generateResponse: function(message) {17 return {18 };19 }20};21exports.generateResponse = function(message) {22 return {23 };24};
Using AI Code Generation
1var root = require('root');2var response = root.generateResponse();3exports.generateResponse = function(){4};5module.exports = object;6exports.generateResponse = function(){7};8Node.js module import syntax9var object = require('module_name');10var root = require('root');11var response = root.generateResponse();12module.exports = object;13exports.generateResponse = function(){
Using AI Code Generation
1var generateResponse = require('root').generateResponse;2var response = generateResponse('200','OK','Hello World');3console.log(response);4exports.generateResponse = function(statusCode, statusMessage, body){5 return {6 };7};8{ statusCode: '200', statusMessage: 'OK', body: 'Hello World' }
Using AI Code Generation
1var rootModel = require('rootModel');2var response = rootModel.generateResponse(200, 'Success');3console.log(response);4module.exports = {5 generateResponse: function(status, message) {6 return { status: status, message: message };7 }8};9var rootModel = require('rootModel');10var response = rootModel.generateResponse(200, 'Success');11console.log(response);12(function (exports, require, module, __filename, __dirname) {13});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!