How to use isPromise method in root

Best JavaScript code snippet using root

users.service.js

Source:users.service.js Github

copy

Full Screen

1/**2 * Created by a.elkayam on 03/11/13.3 */4/**5 * Created with JetBrains WebStorm.6 * User: a.elkayam7 * Date: 15/09/138 * Time: 17:399 * To change this template use File | Settings | File Templates.10 */11var userService = module.exports = new userService();12// This is here and not on the top because licenseService call userService13// which create circular dependency14var licenseService = require('../../common/services/license.service');15var groupService = require('../groups/groups.service');16var applicationError = require('../../common/errors/ApplicationErrors');17var userMongo = require('./users.dal');18var groupMongo = require('../groups/groups.dal');19var userFactory = require('./users.factory');20var objectID = require('mongodb').ObjectID;21var promiseHandler = require('../../common/promise');22var serverEnvironment = require('../../common/serverEnvironment');23var mailTemplateSender = require('../emails/mailTemplateSender');24const logger = require('../../common/logger').default('users-service');25var Q = require('q');26var server = require('../../common/server');27var util = require('util');28var validator = require('../../common/utils/validator.util');29var _ = require('underscore');30var roleReadService = require('../roles/roleRead.service');31var ldapService = require('../ldap/ldap.service');32var ldapDomainsService = require('../ldapDomains/v1/ldapDomains.service');33var ldapDomainsErrors = require('../ldapDomains/v1/ldapDomains.errors');34var principalRemoval = require('../../common/principalRemoval.event');35var adGroupDeleted = require('../ldap/adGroupDeleted.event');36var stringUtils = require('../../common/utils/string.util');37var hashService = require('../../common/security/hash');38var crypto = require('crypto');39var dbUtils = require('../../common/dal/dbUtils');40var DO_PROMISE = true;41var EXPIRATION_TIME = 604800;42// subscribe to the event of principal removal43adGroupDeleted.register(userService.deleteByGroupSid);44function userService() {45 var self = this;46 this.findByQuery = function (limit, skip, query, orderByField) {47 return userMongo.findAll(limit, skip, orderByField, query, null, true)48 .then(function (users) {49 var attachRoleNameQueue = [];50 _.each(users, function(user){51 attachRoleNameQueue.push(attacheRoleNameAndBaseRoleName(user));52 });53 return Q.all(attachRoleNameQueue);54 })55 .catch(function (error) {56 server.err(error);57 })58 };59 this.findUserByEmailUserName = function(emailOrUserName, checkActive){60 var escapedEmailOrUserName = stringUtils.escapeRegExp(emailOrUserName);61 var query = {$or:[{'userName': { "$regex" : '^' +escapedEmailOrUserName + '$', "$options" : "-i" }},{'email': { "$regex" : '^' +escapedEmailOrUserName + '$', "$options" : "-i" }}]};62 if (checkActive){63 query.active = true;64 }65 return userMongo.getUserByQueryPromise(query)66 .then(function (user){67 return attacheRoleNameAndBaseRoleName(user);68 }).then(function (user){69 if (!user){70 return null;71 }72 if(user.activeDirectory){73 return self.getGroups(user, null, DO_PROMISE)74 .then(function(groups){75 user.resolevdGroups = _.chain(groups).pluck('_id').map(function(x){ return x.toHexString(); }).value();76 //send respone77 return user;78 });79 } else {80 //send respone81 return user;82 }83 });84 }85 this.findUsers = function(limit,skip,search,groups,orderByField,isDesc, onlyAD, groupsNames, includeDomain, callback,isPromise)86 {87 var deferredObj = Q.defer();88 var searchSpaceSplit = [];89 if(search) {90 searchSpaceSplit = search.split(" ");91 // This escaping is for situation when we pass email with +92 // sign. and we don't want it to bo part of the regex93 // special signs but part of the string to search94 search = stringUtils.escapeRegExp(search);95 }96 var query = { };97 if( search ){98 query = {99 $or:[100 {userName: new RegExp(search,"i")},101 {email: new RegExp(search,"i")},102 {lastName: new RegExp(search,"i")},103 {firstName: new RegExp(search,"i")}104 ]105 };106 }107 if( searchSpaceSplit.length >1 ){108 if( _.isArray( query.$or ) ){109 query.$or.push( {110 lastName: new RegExp( stringUtils.escapeRegExp( searchSpaceSplit[ 0 ] ), "i" ),111 firstName: new RegExp( stringUtils.escapeRegExp( searchSpaceSplit[ 1 ] ), "i" )112 } );113 query.$or.push( {114 lastName: new RegExp( stringUtils.escapeRegExp( searchSpaceSplit[ 1 ] ), "i" ),115 firstName: new RegExp( stringUtils.escapeRegExp( searchSpaceSplit[ 0 ] ), "i" )116 } );117 }118 }119 if( onlyAD ){120 query.activeDirectory = true;121 }122 if( groups && ~groups.length ){123 query = {124 $and: [125 query,126 {127 $or: [128 { groups: { $elemMatch: { $in: groups } } },129 { adgroups: { $elemMatch: { $in: groups } } }130 ]131 }132 ]133 }134 }135 var orderBy = {};136 var orderByFieldsArr = [];137 if(orderByField)138 {139 orderByFieldsArr = orderByField.split(',');140 orderByFieldsArr.forEach(function(field){141 orderBy[field] = isDesc? -1:1;142 });143 }144 userMongo.findAll(limit,skip,orderBy,query, function (err, items) {145 //check for database error146 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);147 var attachRoleNameQueue = [];148 _.each(items, function(user){149 attachRoleNameQueue.push(attacheRoleNameAndBaseRoleName(user));150 });151 Q.all(attachRoleNameQueue)152 .then(function (users) {153 if (includeDomain) {154 return ldapDomainsService.getDomainDetailsForEntity(users);155 } else {156 return users;157 }158 })159 .then(function (items){160 if (!groupsNames){161 //send response162 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,items);163 }164 // getting the groups names165 var getGroupsPromises = [];166 for (var i = 0; i < items.length; i++) {167 var user = items[i];168 getGroupsPromises.push(self.getGroups(user, null, DO_PROMISE));169 }170 Q.all(getGroupsPromises)171 .then(function (results) {172 for (var i = 0; i < results.length; i++) {173 var groupResult = results[i];174 var user = items[i];175 user.groups = groupResult;176 }177 //send response178 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, items);179 })180 .catch(function (err) {181 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, new applicationError.Database(err), null);182 });183 });184 });185 if(isPromise) return deferredObj.promise;186 };187 this.isUsersExist = function (users) {188 var deferred = Q.defer();189 var promisesQueue = [];190 for (var i = 0; i < users.length; i++) {191 var user = users[i];192 // var email = user.mail || user.email;193 // var escapedEmail = stringUtils.escapeRegExp(email);194 // var escapedUserName = stringUtils.escapeRegExp(stringUtils.emailPrefix(user.userPrincipalName));195 // var query = {$or:[196 // {'userName': { "$regex" : '^' +escapedEmail + '$', "$options" : "-i" }},{'email': { "$regex" : '^' +escapedEmail + '$', "$options" : "-i" }},197 // {'userName': { "$regex" : '^' +escapedUserName + '$', "$options" : "-i" }},{'email': { "$regex" : '^' +escapedUserName + '$', "$options" : "-i" }}198 // ]};199 var uname;200 var principalName = user.principalName || user.userPrincipalName;201 if (principalName && principalName.indexOf('@') !== -1){202 uname = principalName.substr(0, principalName.indexOf('@'));203 } else {204 uname = principalName;205 }206 var queryOrArray = [{ userName: uname}, { principalName: user.userPrincipalName }];207 if (user.objectSid) queryOrArray.push({ objectSid: user.objectSid});208 var query = { $or: queryOrArray, ldapDomainId: user.domain._id };209 promisesQueue.push(userMongo.getUserByQueryPromise(query));210 }211 Q.all(promisesQueue)212 .then(function (results) {213 for (var i = 0; i < results.length; i++) {214 var userResult = results[i];215 var user = users[i];216 user.isExist = userResult != undefined && userResult != null;217 }218 deferred.resolve(users);219 })220 .catch(function (err) {221 deferred.reject(err);222 });223 return deferred.promise;224 };225 this.findAdUsers = function(domainIdOrName, limit, search, checkExist, callback, isPromise) {226 var deferredObj = Q.defer();227 ldapService.findUsers(domainIdOrName, limit, search, function (err, adUsers) {228 //check for database error229 if (err) {230 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, err, null);231 }232 if (!checkExist){233 //send response234 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, adUsers);235 }236 self.isUsersExist(adUsers)237 .then(function (users) {238 //send response239 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, users);240 })241 .catch(function (err) {242 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, new applicationError.Database(err), null);243 });244 });245 if (isPromise){246 return deferredObj.promise;247 }248 };249 this.countUsers = function(search,callback,isPromise)250 {251 var deferredObj = Q.defer();252 var query = {};253 var searchSpaceSplit = [];254 if(search) {255 searchSpaceSplit = search.split(" ");256 // This escaping is for situation when we pass email with +257 // sign. and we don't want it to bo part of the regex258 // special signs but part of the string to search259 search = stringUtils.escapeRegExp(search);260 }261 if(search) query = {$or:[{userName: new RegExp(search,"i")},{email: new RegExp(search,"i")},{lastName: new RegExp(search,"i")},{firstName: new RegExp(search,"i")}]};262 if(searchSpaceSplit.length >1)263 {264 if (_.isArray(query.$or)) {265 query.$or.push({lastName: new RegExp(stringUtils.escapeRegExp(searchSpaceSplit[0]), "i"), firstName: new RegExp(stringUtils.escapeRegExp(searchSpaceSplit[1]), "i")});266 query.$or.push({lastName: new RegExp(stringUtils.escapeRegExp(searchSpaceSplit[1]), "i"), firstName: new RegExp(stringUtils.escapeRegExp(searchSpaceSplit[0]), "i")});267 }268 }269 userMongo.count(query, function (err, result) {270 //check for database error271 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);272 //send response273 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);274 });275 if(isPromise) return deferredObj.promise;276 };277 /**278 * Function to count how many users there is from each base role (279 * include children of the base role)280 * @return {Object} object with the keys represents the base roles names281 * and the value are the count of users from each role282 */283 this.countUsersBaseRoles = function(){284 var baseRoleGroups = {285 super : 0,286 admin : 0,287 contributor : 0,288 consumer : 0289 };290 var usersCountByRoles;291 // Get count users by roles292 return userMongo.countUsersByRoles()293 .then(function (result){294 usersCountByRoles = result;295 return roleReadService.getAllRoles({includeBaseRolesName : true});296 }).then(function (allRoles){297 // Map the roles count to base roles count298 _.each(usersCountByRoles, function (roleCount){299 // Find the role itself300 var role = _.find(allRoles, function(role){301 // Take care of users without roleId302 // count them as consumers303 if (!roleCount._id){304 return role.name === "consumer";305 }306 return role._id.toString() === roleCount._id.toString();307 });308 var baseRoleName = role.baseRoleName;309 // Set the count310 baseRoleGroups[baseRoleName] += roleCount.count;311 });312 return baseRoleGroups;313 });314 }315 this.findById = function(userId,callback,isPromise)316 {317 var deferredObj = Q.defer();318 userMongo.findById(userId, function (err, item) {319 //check for database error320 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);321 //check if userItem found322 if (!item) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);323 attacheRoleNameAndBaseRoleName(item)324 .then(function (item){325 if(item.activeDirectory){326 self.getGroups(item, function(err, groups){327 if (err) {return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);}328 item.resolevdGroups = _.chain(groups).pluck('_id').map(function(x){ return x.toHexString(); }).value();329 //send respone330 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);331 });332 } else {333 //send respone334 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);335 }336 });337 });338 if(isPromise) return deferredObj.promise;339 };340 this.findByIdUsername = function(value,callback,isPromise)341 {342 var deferredObj = Q.defer();343 userMongo.findByIdUsername(value, function (err, item) {344 //check for database error345 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);346 //check if userItem found347 if (!item) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);348 attacheRoleNameAndBaseRoleName(item)349 .then(function (item){350 if(item.activeDirectory){351 self.getGroups(item, function(err, groups){352 if (err) {return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);}353 item.resolevdGroups = _.chain(groups).pluck('_id').map(function(x){ return x.toHexString(); }).value();354 //send respone355 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);356 });357 } else {358 //send respone359 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);360 }361 });362 });363 if(isPromise) return deferredObj.promise;364 };365 this.findByRoleId = function(roleId){366 return userMongo.findByRoleId(roleId);367 };368 this.findByRoleName = function (name) {369 return roleReadService.getRoleByIdOrName(name)370 .then(function (role) {371 if (!role) throw 'could not find role with name ' + name;372 return self.findByRoleId(role._id);373 });374 };375 this.findByEmail = function(email,callback,isPromise)376 {377 var deferredObj = Q.defer();378 userMongo.findByEmail(email, function (err, item) {379 //check for database error380 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);381 //check if userItem found382 if (!item) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,null);383 attacheRoleNameAndBaseRoleName(item)384 .then(function (item){385 if(item.activeDirectory){386 self.getGroups(item, function(err, groups){387 if (err) {return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);}388 item.resolevdGroups = _.chain(groups).pluck('_id').map(function(x){ return x.toHexString(); }).value();389 //send respone390 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);391 });392 } else {393 //send respone394 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);395 }396 });397 });398 if(isPromise) return deferredObj.promise;399 };400 this.findByUserName = function(userName,callback,isPromise)401 {402 var deferredObj = Q.defer();403 userMongo.findByUserName(userName, function (err, item) {404 //check for database error405 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);406 //check if userItem found407 if (!item) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);408 attacheRoleNameAndBaseRoleName(item)409 .then(function (item){410 if(item.activeDirectory){411 self.getGroups(item, function(err, groups){412 if (err) {return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);}413 item.resolevdGroups = _.chain(groups).pluck('_id').map(function(x){ return x.toHexString(); }).value();414 //send respone415 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);416 });417 } else {418 //send respone419 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);420 }421 });422 });423 if(isPromise) return deferredObj.promise;424 };425 this.findByIds = function(idsList, callback, isPromise, includeDomain)426 {427 var deferredObj = Q.defer();428 for (var i = 0, l = idsList.length; i < l; i++) {429 idsList[i] = new objectID(idsList[i]);430 }431 var query = {432 _id: { "$in": idsList }433 };434 userMongo.getUsersByQuery(query, function (err, users) {435 // check for database error436 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);437 // check if no were userItem found438 if (!users) return promiseHandler.promiseCallback(callback,isPromise,439 deferredObj, new applicationError.NotFound("there is no users for the given ids list"), null);440 var attachRoleNameQueue = [];441 _.each(users, function(user){442 attachRoleNameQueue.push(attacheRoleNameAndBaseRoleName(user));443 });444 Q.all(attachRoleNameQueue)445 .then(function (users) {446 if (includeDomain) {447 return ldapDomainsService.getDomainDetailsForEntity(users);448 } else {449 return users;450 }451 })452 .then(function (users){453 // send response454 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, users);455 });456 });457 if(isPromise) return deferredObj.promise;458 };459 this.simulate = function(emailList, admode, ldapDomainId, callback,isPromise)460 {461 var deferredObj = Q.defer();462 var retObject = {users:[],license:{}};463 var emailsQuery = [];464 var toBeAdded = [];465 var newEmailLst = [];466 var notValidEmailLst = [];467 emailList.forEach(function(email){468 if(validator.validEmail(email) || admode){469 // This escaping is for situation when we pass email with +470 // sign. and we don't want it to bo part of the regex471 // special signs but part of the string to search472 escapedEmail = stringUtils.escapeRegExp(email);473 emailsQuery.push({'userName': { "$regex" : "^"+ escapedEmail +"$", "$options" : "-i" }});474 emailsQuery.push({'email': { "$regex" :"^"+ escapedEmail +"$", "$options" : "-i" }});475 newEmailLst.push(email);476 }477 else478 {479 notValidEmailLst.push(email);480 }481 });482 var query = {$or:emailsQuery};483 if (admode) query = {$and: [query, {ldapDomainId: dbUtils.createId(ldapDomainId)}]};484 if(!newEmailLst.length) query = {'none':'none'};485 userMongo.findAll(null,null,{},query,function(err,items){486 //check for database error487 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);488 if (admode){489 retObject.users = _.map(items,function(item){return {exist:true,roleId:"consumer",userName:item.userName};});490 newEmailLst.forEach(function(userName){491 var filterResult = _.filter(retObject.users,function(user){return userName.toLowerCase() === user.userName.toLowerCase();});492 if(!filterResult.length) retObject.users.push({exist:false,roleId:"consumer",userName:userName});493 toBeAdded.push({exist:false,roleId:"consumer",userName:userName});494 });495 } else {496 retObject.users = _.map(items,function(item){return {exist:true,roleId:"consumer",email:item.email};});497 newEmailLst.forEach(function(email){498 var filterResult = _.filter(retObject.users,function(user){return email.toLowerCase() === user.email.toLowerCase();});499 if(!filterResult.length) retObject.users.push({exist:false,roleId:"consumer",email:email});500 toBeAdded.push({exist:false,roleId:"consumer",email:email});501 });502 }503 licenseService.getLeftLicenses()504 .then(function(leftLicenses){505 retObject.license = leftLicenses;506 //send response507 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,retObject);508 });509 });510 if(isPromise) return deferredObj.promise;511 };512 this.addUser = function(user,addingUser,callback,isPromise)513 {514 var deferredObj = Q.defer();515 var promiseUpdatePassword = user.password ? hashService.create(user.password).then(function (newHash) {516 user.hash = newHash;517 }) : Q.when();518 promiseUpdatePassword.then(function () {519 userFactory.create(user)520 .then(function (newUser){521 var queryOrArray = [];522 if (newUser.email) queryOrArray.push({'email': { "$regex" : '^' + stringUtils.escapeRegExp(newUser.email) + '$', "$options" : "i" }});523 if (newUser.userName) {524 queryOrArray.push( {'email': { "$regex" : '^' + stringUtils.escapeRegExp(newUser.userName) + '$', "$options" : "i" }});525 queryOrArray.push( {'userName': { "$regex" : '^' + stringUtils.escapeRegExp(newUser.userName) + '$', "$options" : "i" },526 activeDirectory: {$ne: true}});527 }528 var query = {$or: queryOrArray};529 //check if user already exist530 userMongo.getUserByQuery(query, function(err,userItem) {531 //check for database error532 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);533 if(userItem) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.badRequest('User already exist'),null);534 // add user535 userMongo.add(newUser, function (err, items) {536 //check for database error537 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);538 if (newUser.email) {539 mailTemplateSender.userCreated(addingUser,newUser,function(err,result){540 if(err) logger.error('userCreated mail fail to sent ' +err);541 //send response542 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,items);543 });544 } else {545 //send response546 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,items);547 }548 });549 });550 });551 });552 if(isPromise) return deferredObj.promise;553 };554 this.addAdUser = function(users,addingUser,sendCreatedMail,callback,isPromise)555 {556 var deferredObj = Q.defer();557 ldapDomainsService.attachValidLdapDomain(users)558 .then(function (users) {559 var addUserQueue = [];560 users.forEach(function(user){561 addUserQueue.push(addADUser(user,null,true));562 });563 var addedUsers;564 var addResults = {};565 Q.all(addUserQueue)566 .then(function(results) {567 addResults.noActiveDirectoryUsers = _.filter(results,function(item){return !item.exists;});568 addedUsers = _.filter(results,function(item){return item.exists;});569 addedUsers = _.map(addedUsers,function(item){return item.user;});570 addResults.addedUsers = [];571 if(!addedUsers.length) {572 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,addResults);573 }574 return checkExistence(addedUsers);575 }).then(function () {576 userMongo.add(addedUsers, function (err, items) {577 //check for database error578 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);579 // Sending notification mail (non-blocking)580 if (sendCreatedMail){581 var url = serverEnvironment.getUserLoginUrl();582 _.each(items.filter(user => user.email),function(user){583 mailTemplateSender.userCreatedFromAD(addingUser,user,url);584 })585 }586 //send response587 addResults.addedUsers = items;588 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,addResults);589 });590 })591 .catch(function(err) {592 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,err,null);593 });594 }).catch(function (err) {595 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, new applicationError.badRequest(err), null);596 });597 if(isPromise) return deferredObj.promise;598 };599 function checkExistence(users) {600 var queryOrArray = [];601 users.forEach(user => {602 var userEmail = user.email || user.mail;603 if (userEmail) queryOrArray.push({'email': { "$regex" : '^' + stringUtils.escapeRegExp(userEmail) + '$', "$options" : "i" }});604 if (user.userName) queryOrArray.push({'email': { "$regex" : '^' + stringUtils.escapeRegExp(user.userName) + '$', "$options" : "i" }});605 var innerOrQuery = [];606 if (user.userName) innerOrQuery.push({'userName': { "$regex" : '^' + stringUtils.escapeRegExp(user.userName) + '$', "$options" : "i" }});607 if (user.principalName) innerOrQuery.push({'principalName': { "$regex" : '^' + stringUtils.escapeRegExp(user.principalName) + '$', "$options" : "i" }});608 if (user.objectSid) innerOrQuery.push({'objectSid': user.objectSid});609 if (innerOrQuery.length > 0) queryOrArray.push({activeDirectory: true, ldapDomainId: dbUtils.createId(user.ldapDomainId), $or: innerOrQuery});610 });611 return userMongo.getUsersByQueryPromise({ $or: queryOrArray })612 .then(function (alreadyExistUsers) {613 if (alreadyExistUsers.length > 0) {614 throw (new applicationError.badRequest('User name or email already exists'));615 }616 });617 }618 function addADUser(user,callback,isPromise)619 {620 var deferredObj = Q.defer();621 ldapDomainsService.getLdapDomain(user.ldapDomainId, undefined, undefined, {includeDecryptedPassword: true}).then(function (ldapDomain) {622 if (!ldapDomain) {623 return promiseHandler.promiseCallback(callback, isPromise,deferredObj,624 new applicationError.badRequest(new ldapDomainsErrors.LdapDomainNotFoundError(user.ldapDomainId)), null);625 }626 if (!ldapDomain.enabled) {627 return promiseHandler.promiseCallback(callback, isPromise, deferredObj,628 new applicationError.badRequest(new ldapDomainsErrors.LdapDomainDisabled(user.ldapDomainId)), null);629 }630 var ldapDomainObject = ldapDomainsService.createLdapDomainObject(ldapDomain);631 ldapService.findUser(user.dn || user.userName, ldapDomainObject, function(err, ADuser) {632 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj, err, null);633 if (!ADuser) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,{user:user,exists:false});634 ADuser.roleId = user.roleId;635 ADuser.ldapDomainId = user.ldapDomainId;636 userFactory.createAdUser(ADuser)637 .then(function (newUser){638 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,{user:newUser,exists:true});639 });640 });641 });642 if(isPromise) return deferredObj.promise;643 }644 this.inviteUser = function(inviteId,user,callback,isPromise)645 {646 var deferredObj = Q.defer();647 var email = user.email;648 var needActivation = true;649 var generatedToken;650 Q.when(crypto.randomBytes(20))651 .then(function (token) {652 if (!token) {653 // what exception should be thrown here?654 throw 'faild to generate token';655 }656 generatedToken = token.toString('hex');657 user.activationToken = generatedToken;658 user.activationExpires = Date.now() + (1000 * EXPIRATION_TIME);659 return userFactory.create(user, needActivation)660 })661 .then(function (invitedUser) {662 // get admin user663 self.findById(inviteId.id,function(err,adminUser){664 // add user665 userMongo.add(invitedUser, function (err, items) {666 //check for database error667 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);668 var url = util.format(serverEnvironment.getUserActivationUrl(), generatedToken);669 mailTemplateSender.newUserInvitation(adminUser,invitedUser,url,function(err,result){670 if(err) logger.error('newUserInvitation mail fail to sent ' +err);671 if(!err) logger.info('newUserInvitation mail sent' +result);672 });673 //send response674 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,true);675 });676 });677 });678 if(isPromise) return deferredObj.promise;679 };680 this.forgetPassword = function(email,callback,isPromise)681 {682 var deferredObj = Q.defer();683 var forgetPasswordUser = userFactory.forgetPassword();684 var query = {email:email};685 userMongo.getUserByQuery(query,function(err,userItem){686 if (err) {687 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);688 }689 else if (!userItem){690 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("email not found"),null);691 }692 else693 {694 userMongo.update(userItem._id.toHexString(),forgetPasswordUser,function(err,result){695 var url = util.format(serverEnvironment.getUserForgetPasswordUrl(), userItem._id.toHexString(),userItem.userName);696 mailTemplateSender.passwordRecovery(userItem,url,function(err,result){697 if(err) logger.error('passwordRecovery mail fail to sent ' +err);698 if(!err) logger.info('passwordRecovery mail sent' +result);699 });700 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,true);701 });702 }703 });704 if(isPromise) return deferredObj.promise;705 };706 this.inviteUsers = function(shareNewArr,callback,isPromise)707 {708 var deferredObj = Q.defer();709 var newUserLst = [];710 var newUserLstQueue = [];711 function createInvitedUser(email, roleId, dashboardRule){712 var DO_NEED_ACTIVATION = true;713 var invitedUser = {714 email : email,715 roleId: roleId,716 dashboardRule : dashboardRule717 };718 var token = crypto.randomBytes(20).toString('hex');719 if (!token) {720 // what exception should be thrown here?721 throw 'faild to generate token';722 }723 invitedUser.activationToken = token.toString('hex');724 invitedUser.activationExpires = Date.now() + (1000 * EXPIRATION_TIME);725 return userFactory.create(invitedUser, DO_NEED_ACTIVATION);726 }727 shareNewArr.forEach(function(shareNewArr){728 newUserLstQueue.push(createInvitedUser(shareNewArr.email, shareNewArr.roleId, shareNewArr.rule));729 });730 Q.all(newUserLstQueue)731 .then(function (newUserLst){732 if(newUserLst.length === 0) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,newUserLst);733 // add user734 userMongo.add(newUserLst, function (err, items) {735 //check for database error736 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);737 //send response738 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,items);739 });740 });741 if(isPromise) return deferredObj.promise;742 };743 this.activateUser = function(user,userObj,callback,isPromise)744 {745 var deferredObj = Q.defer();746 var activateUser = userFactory.activateUser(userObj);747 //check if user already exist748 userMongo.updateByIdUsername(user, activateUser, function(err,result) {749 //check for database error750 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);751 //check if userItem found752 if (!result) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user can not activate"),null);753 //send response754 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);755 });756 if(isPromise) return deferredObj.promise;757 };758 this.recoverPassword = function(userId,user,callback,isPromise)759 {760 var deferredObj = Q.defer();761 var recoverPasswordUser = userFactory.recoverPasswordUser(user);762 //check if user already exist763 userMongo.update(userId,recoverPasswordUser, function(err,result) {764 //check for database error765 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);766 //check if userItem found767 if (!result) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user can not activate"),null);768 //send response769 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);770 });771 if(isPromise) return deferredObj.promise;772 };773 this.updateUser = function(userId,updateUser,callback,isPromise, shouldUpdateAsIs)774 {775 var deferredObj = Q.defer();776 userFactory.update(updateUser)777 .then(function (updateUser){778 var callbackFn = function (err, result) {779 //check for database error780 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);781 //check if userItem found782 if (!result) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);783 //send response784 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);785 };786 userMongo.update(userId, updateUser, callbackFn, shouldUpdateAsIs);787 });788 if(isPromise) return deferredObj.promise;789 };790 this.updateUserByIdUsername = function(user, updateUser, callback, isPromise) {791 var deferredObj = Q.defer();792 var promiseUpdatePassword = updateUser.password ? hashService.create(updateUser.password).then(function (newHash) {793 updateUser.hash = newHash;794 }) : Q.when();795 promiseUpdatePassword.then(function () {796 userFactory.update(updateUser)797 .then(function (updateUser){798 userMongo.updateByIdUsername(user, updateUser, function (err, result) {799 //check for database error800 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);801 //check if userItem found802 if (!result) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);803 //send response804 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);805 });806 });807 });808 if(isPromise) return deferredObj.promise;809 };810 this.deleteUser = function(userId,callback,isPromise)811 {812 var deferredObj = Q.defer();813 userMongo.delete(userId, function (err, result) {814 //check for database error815 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);816 //check if userItem found817 if (!result) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);818 // delete the group from all the resources819 principalRemoval.notifyObservers([{ id: userId, type: 'user' }]);820 //send respone821 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);822 });823 if(isPromise) return deferredObj.promise;824 };825 this.deleteUserByIdUsername = function(user,callback,isPromise)826 {827 var deferredObj = Q.defer();828 userMongo.findByIdUsername(user, function (err, selectedUser) {829 //check for database error830 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);831 //check if userItem found832 if (!selectedUser) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);833 userMongo.deleteByIdUsername(user, function (err, result) {834 //check for database error835 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);836 //check if userItem found837 if (!result) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);838 // delete the group from all the resources839 principalRemoval.notifyObservers([{ id: selectedUser._id && selectedUser._id.toHexString(), type: 'user' }]);840 //send response841 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);842 });843 });844 if(isPromise) return deferredObj.promise;845 };846 this.getGroups = function(user, callback, isPromise){847 var deferredObj = Q.defer();848 var query = {};849 var isAD = user.activeDirectory || false;850 var userGroups = isAD ? user.adgroups : user.groups;851 var groupsResult;852 groupService.findGroupsByArray(userGroups, isAD, true, null, DO_PROMISE)853 .then(function (groups){854 groupsResult = groups;855 if (isAD && user.groups && !_.isEmpty(user.groups)){856 // case ad user with mixed groups857 groupService.findGroupsByArray(user.groups, false, true, null, DO_PROMISE)858 .then(function (groups){859 groupsResult = _.union(groupsResult, groups);860 //send response861 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, groupsResult);862 })863 .fail(function (err) {864 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, new applicationError.Database(err), null);865 });866 } else {867 //case internal or ad not mixed groups user868 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, groupsResult);869 }870 }).fail(function (err){871 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, new applicationError.Database(err), null);872 });873 if(isPromise) return deferredObj.promise;874 };875 this.getGroupsIncludingBuiltInGroups = function(user){876 var groups;877 return self.getGroups(user, null, DO_PROMISE)878 .then(function(g){879 groups = g || [];880 var query = {"$or" : [{everyone : true}]};881 if (user.baseRoleName === "super" || user.baseRoleName === "admin"){882 query.$or.push({admins : true});883 }884 return Q.ninvoke(groupMongo, "getGroupsByQuery", query);885 }).then(function(builtInGroups){886 var allGroups = groups.concat(builtInGroups);887 return allGroups;888 });889 }890 this.findByGroupId = function (groupId, callback, isPromise) {891 var deferredObj = Q.defer();892 userMongo.findByGroupId(groupId, function (err, users) {893 //check for database error894 if (err) {895 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, new applicationError.Database(err), null);896 }897 var attachRoleNameQueue = [];898 _.each(users, function(user){899 attachRoleNameQueue.push(attacheRoleNameAndBaseRoleName(user));900 });901 Q.all(attachRoleNameQueue)902 .then(function (users){903 //send response904 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, users);905 });906 });907 if(isPromise) {908 return deferredObj.promise;909 }910 };911 this.findByGroupSid = function (groupSid, callback, isPromise) {912 var deferredObj = Q.defer();913 userMongo.findByGroupSid(groupSid, function (err, users) {914 //check for database error915 if (err) {916 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, new applicationError.Database(err), null);917 }918 var attachRoleNameQueue = [];919 _.each(users, function(user){920 attachRoleNameQueue.push(attacheRoleNameAndBaseRoleName(user));921 });922 Q.all(attachRoleNameQueue)923 .then(function (users){924 //send response925 return promiseHandler.promiseCallback(callback, isPromise, deferredObj, null, users);926 });927 });928 if(isPromise) {929 return deferredObj.promise;930 }931 };932 this.addGroup = function (user, groupId, callback, isPromise) {933 var deferredObj = Q.defer();934 userMongo.findByIdUsername(user, function(err, userItem) {935 //check for database error936 if (err) {937 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);938 }939 //check if userItem found940 if (!userItem) {941 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);942 }943 if (userItem.groups && userItem.groups.length > 0 && _.contains(userItem.groups, groupId)){944 // user already has the groupId945 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null, userItem._id.toHexString());946 }947 // add the groupId to the user948 userMongo.addGroup(userItem._id.toHexString(), groupId, function (err, item) {949 //check for database error950 if (err) {951 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);952 }953 // send response954 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null, userItem._id.toHexString());955 });956 });957 if(isPromise) {958 return deferredObj.promise;959 }960 };961 this.removeGroup = function (user, groupId, callback, isPromise) {962 var deferredObj = Q.defer();963 userMongo.findByIdUsername(user, function(err, userItem) {964 //check for database error965 if (err) {966 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);967 }968 //check if userItem found969 if (!userItem) {970 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user not found"),null);971 }972 if (userItem.groups && userItem.groups.length > 0 && !_.contains(userItem.groups, groupId)){973 // user does not has the groupId974 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("user does not has this group"),null);975 }976 // remove the groupId from the user977 userMongo.removeGroup(userItem._id.toHexString(), groupId, function (err, item) {978 //check for database error979 if (err) {980 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);981 }982 // send response983 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null, userItem._id.toHexString());984 });985 });986 if(isPromise) {987 return deferredObj.promise;988 }989 };990 this.validateEmails = function(emails, callback, isPromise) {991 var deferredObj = Q.defer();992 var reqEmails = _.map(emails, function (x) { return new RegExp("^" + stringUtils.escapeRegExp(x) + "$", "i"); });993 var query = { email: {$in: reqEmails} };994 userMongo.findAll(null,null,{},query, function (err, items) {995 //check for database error996 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);997 var result = {998 isValid: false,999 existingUsers: items1000 };1001 result.isValid = items && (items.length === emails.length);1002 //send response1003 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);1004 });1005 if(isPromise) return deferredObj.promise;1006 };1007 this.deleteByGroupSid = function(groupId,groupSid,deleteUsers)1008 {1009 var deferredObj = Q.defer();1010 if (deleteUsers){1011 var usersToDelete = [];1012 var principals = [];1013 var usersToCheckQueue = [];1014 var currUser;1015 var checkUser = function(user){1016 return groupService.findGroupsByArray(user.adgroups, true, true, null, DO_PROMISE)1017 .then(function (groups){1018 if (groups.length === 0){1019 return user._id;1020 } else {1021 return;1022 }1023 });1024 };1025 userMongo.findByGroupSid(groupSid, function (err, users) {1026 //check for database error1027 if (err) {return false;}1028 _.each(users, function(user){1029 currUser = user;1030 usersToCheckQueue.push(checkUser(user));1031 });1032 Q.all(usersToCheckQueue)1033 .then(function (results){1034 /*usersToDelete = _.reject(results, function(user){1035 return !user;1036 });1037 var principals = _.map(usersToDelete, function(userId){1038 return {1039 id : userId.toString(),1040 type : 'user'1041 };1042 });*/1043 _.each(results, function(userId){1044 if (userId){1045 usersToDelete.push(userId);1046 principals.push({ id : userId.toHexString(), type : 'user'});1047 }1048 });1049 var query = {'_id' : {$in: usersToDelete}};1050 userMongo.deleteByQuery(query, function (err, result) {1051 if (err) {return false;}1052 principalRemoval.notifyObservers(principals);1053 return true;1054 });1055 }).fail(function(err) {1056 return false;1057 });1058 });1059 return deferredObj.promise;1060 } else {1061 return Q.fcall(function () {1062 return true;1063 });1064 }1065 };1066 function attacheRoleNameAndBaseRoleName(user){1067 if (!user){1068 return Q.when(null);1069 }1070 return Q.all([roleReadService.getRoleByIdOrName(user.roleId),1071 roleReadService.getBaseRoleByRoleIdOrName(user.roleId)])1072 .spread(function(role, baseRole){1073 user.roleName = role.name;1074 user.baseRoleName = baseRole.name;1075 return user;1076 }).catch(function(err){1077 logger.error('Error attaching role and base role name for user : ', user, 'Error : ', err);1078 return user;1079 });1080 }...

Full Screen

Full Screen

is-promise.test.js

Source:is-promise.test.js Github

copy

Full Screen

...3import babel from './helpers/babel';4import espree from './helpers/espree';5[espree, babel].forEach(({name, utils}) => {6 test(`(${name}) should return false if node is falsy or not a node`, t => {7 t.false(lib.isPromise(null));8 t.false(lib.isPromise(undefined));9 t.false(lib.isPromise({}));10 t.false(lib.isPromise('foo'));11 });12 test(`(${name}) should return true if node is call expression which calls '.then()'`, t => {13 t.true(lib.isPromise(utils.expression(`foo.then(fn)`)));14 t.true(lib.isPromise(utils.expression(`foo().then(fn)`)));15 t.true(lib.isPromise(utils.expression(`foo['then'](fn)`)));16 t.true(lib.isPromise(utils.expression(`foo['th' + 'en'](fn)`)));17 t.false(lib.isPromise(utils.expression(`foo().bar(fn)`)));18 t.false(lib.isPromise(utils.expression(`then(fn)`)));19 t.false(lib.isPromise(utils.expression(`foo['bar'](fn)`)));20 t.false(lib.isPromise(utils.expression(`foo[0](fn)`)));21 });22 test(`(${name}) should return true if node is call expression which calls '.catch()'`, t => {23 t.true(lib.isPromise(utils.expression(`foo.catch(fn)`)));24 t.true(lib.isPromise(utils.expression(`foo().catch(fn)`)));25 t.true(lib.isPromise(utils.expression(`foo['catch'](fn)`)));26 });27 test(`(${name}) should return false when accessing a property of a Promise`, t => {28 t.false(lib.isPromise(utils.expression(`foo.then(fn).foo`)));29 t.false(lib.isPromise(utils.expression(`foo.catch(fn).foo`)));30 });31 test(`(${name}) should return false when calling a property of a Promise`, t => {32 t.false(lib.isPromise(utils.expression(`foo.then(fn).map(fn)`)));33 t.false(lib.isPromise(utils.expression(`foo.catch(fn).map(fn)`)));34 });35 test(`(${name}) should return true when expression is a call to 'Promise.{resolve|reject|race|all}()`, t => {36 t.true(lib.isPromise(utils.expression(`Promise.resolve(fn)`)));37 t.true(lib.isPromise(utils.expression(`Promise.resolve(fn).then(fn)`)));38 t.true(lib.isPromise(utils.expression(`Promise.resolve(fn).catch(fn)`)));39 t.true(lib.isPromise(utils.expression(`Promise.reject(fn)`)));40 t.true(lib.isPromise(utils.expression(`Promise.race(fn)`)));41 t.true(lib.isPromise(utils.expression(`Promise.all(fn)`)));42 t.true(lib.isPromise(utils.expression(`Promise['resolve'](fn)`)));43 t.true(lib.isPromise(utils.expression(`Promise['reject'](fn)`)));44 t.true(lib.isPromise(utils.expression(`Promise['race'](fn)`)));45 t.true(lib.isPromise(utils.expression(`Promise['all'](fn)`)));46 t.false(lib.isPromise(utils.expression(`bar.resolve(fn)`)));47 t.false(lib.isPromise(utils.expression(`bar.reject(fn)`)));48 t.false(lib.isPromise(utils.expression(`bar.race(fn)`)));49 t.false(lib.isPromise(utils.expression(`bar.all(fn)`)));50 t.false(lib.isPromise(utils.expression(`foo.Promise.resolve(fn)`)));51 t.false(lib.isPromise(utils.expression(`Promise.resolve(fn).map(fn)`)));52 });53 test(`(${name}) should return false when expression is a call to a known non-Promise returning method of 'Promise`, t => {54 t.false(lib.isPromise(utils.expression(`Promise.is(fn)`)));55 t.false(lib.isPromise(utils.expression(`Promise.cancel(fn)`)));56 t.false(lib.isPromise(utils.expression(`Promise.promisify(fn)`)));57 t.false(lib.isPromise(utils.expression(`Promise.promisifyAll(obj)`)));58 });59 // Mostly Bluebird methods60 test(`(${name}) should return true when expression is a call to 'Promise.{anything}() except exceptions`, t => {61 t.true(lib.isPromise(utils.expression(`Promise.map(input, fn)`)));62 t.true(lib.isPromise(utils.expression(`Promise.filter(input, fn)`)));63 t.true(lib.isPromise(utils.expression(`Promise.reduce(input, fn)`)));64 t.true(lib.isPromise(utils.expression(`Promise.each(input, fn)`)));65 t.true(lib.isPromise(utils.expression(`Promise.mapSeries(input, fn)`)));66 t.true(lib.isPromise(utils.expression(`Promise.filter(input, fn)`)));67 t.true(lib.isPromise(utils.expression(`Promise.fromCallback(fn)`)));68 t.true(lib.isPromise(utils.expression(`Promise.fromNode(fn)`)));69 t.true(lib.isPromise(utils.expression(`Promise.using(fn)`)));70 t.true(lib.isPromise(utils.expression(`Promise['map'](fn)`)));71 });72 test(`(${name}) should return true when calling 'new Promise(fn)'`, t => {73 t.true(lib.isPromise(utils.expression(`new Promise(fn);`)));74 t.true(lib.isPromise(utils.expression(`new Promise(fn).then();`)));75 t.false(lib.isPromise(utils.expression(`Promise(fn)`)));76 t.false(lib.isPromise(utils.expression(`new Promise(fn).map(fn)`)));77 t.false(lib.isPromise(utils.expression(`new Foo(fn)`)));78 t.false(lib.isPromise(utils.expression(`new Foo.bar(fn)`)));79 t.false(lib.isPromise(utils.expression(`new Promise.bar(fn)`)));80 t.false(lib.isPromise(utils.expression(`new Promise.resolve(fn)`)));81 t.false(lib.isPromise(utils.expression(`new Foo.resolve(fn)`)));82 });...

Full Screen

Full Screen

authConfig.service.js

Source:authConfig.service.js Github

copy

Full Screen

1/**2 * Created by a.elkayam on 03/11/13.3 */4/**5 * Created with JetBrains WebStorm.6 * User: a.elkayam7 * Date: 15/09/138 * Time: 17:399 * To change this template use File | Settings | File Templates.10 */11var applicationError = require('../../common/errors/ApplicationErrors');12// var navverFactory = require('./navver.factory');13var authConfigMongo = require('./authConfig.dal');14var promiseHandler = require('../../common/promise');15var Q = require('q');16var _ = require('underscore');17var objectID = require('mongodb').ObjectID;18function authConfigService() {19 var self = this;20 this.addauthConfig = function(newauthConfig,callback,isPromise)21 {22 var deferredObj = Q.defer();23 authConfigMongo.add(newauthConfig, function (err, result) {24 //check for database error25 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);26 //send response27 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);28 });29 if(isPromise) return deferredObj.promise;30 }31 32 this.getAuthConfig = function(callback,isPromise)33 {34 var deferredObj = Q.defer();35 authConfigMongo.findAll( function (err, item) {36 if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);37 if (!item) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("nav not found"),null);38 return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);39 });40 if(isPromise) return deferredObj.promise;41 };42 // this.getNavversByID=function(userID,callback,isPromise){43 // var deferredObj = Q.defer();44 // conmentMongo.findByUserID(userID, function (err, item) {45 // if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);46 // if (!item) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.NotFound("nav not found"),null);47 // return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,item);48 // });49 // if(isPromise) return deferredObj.promise;50 // }51 // this.updataNavvers=function(navID,updateObject,callback,isPromise){52 // var deferredObj = Q.defer();53 // updateObjects ={$addToSet:{"childList":updateObject}};54 // conmentMongo.update(navID,updateObjects, function (err, result) {55 // //check for database error56 // if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);57 // if(!result) return promiseHandler.promiseCallback(callback,isPromise, new applicationError.NotFound('nav not found'),null);58 // return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);59 // });60 // }61 // this.getNavvers=function(callback,isPromise)62 // {63 // var deferredObj = Q.defer();64 // navverMongo.findAll(function (err, result) {65 // //check for database error66 // if (err) return promiseHandler.promiseCallback(callback,isPromise,deferredObj,new applicationError.Database(err),null);67 // //send response68 // return promiseHandler.promiseCallback(callback,isPromise,deferredObj,null,result);69 // });70 // if(isPromise) return deferredObj.promise;71 // }72}73authConfigService.instance = null;74authConfigService.getInstance = function(){75 if(this.instance === null){76 this.instance = new authConfigService();77 }78 return this.instance;79}...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

...6var promise = {then: function () {}};7describe('calling isPromise', function () {8 describe('with a promise', function () {9 it('returns true', function () {10 assert(isPromise(promise));11 });12 });13 describe('with null', function () {14 it('returns false', function () {15 assert(isPromise(null) === false);16 });17 });18 describe('with undefined', function () {19 it('returns false', function () {20 assert(isPromise(undefined) === false);21 });22 });23 describe('with a number', function () {24 it('returns false', function () {25 assert(!isPromise(0));26 assert(!isPromise(-42));27 assert(!isPromise(42));28 });29 });30 describe('with a string', function () {31 it('returns false', function () {32 assert(!isPromise(''));33 assert(!isPromise('then'));34 });35 });36 describe('with a bool', function () {37 it('returns false', function () {38 assert(!isPromise(false));39 assert(!isPromise(true));40 });41 });42 describe('with an object', function () {43 it('returns false', function () {44 assert(!isPromise({}));45 assert(!isPromise({then: true}));46 });47 });48 describe('with an array', function () {49 it('returns false', function () {50 assert(!isPromise([]));51 assert(!isPromise([true]));52 });53 });54 describe('with a func', function () {55 it('returns false', function () {56 assert(!isPromise(() => {}));57 });58 });59 describe('with a func with .then method', function () {60 it('returns true', function () {61 const fn = () => {};62 fn.then = () => {};63 assert(isPromise(fn));64 });65 });...

Full Screen

Full Screen

is.js

Source:is.js Github

copy

Full Screen

...3 , isPromise = require("../../promise/is");4describe("promise/is", function () {5 if (typeof Promise === "function") {6 it("Should return true on promise", function () {7 assert.equal(isPromise(Promise.resolve()), true);8 });9 }10 it("Should return false on non-promise thenable", function () {11 assert.equal(isPromise({ then: function () { return true; } }), false);12 });13 it("Should return false on plain object", function () { assert.equal(isPromise({}), false); });14 it("Should return false on function", function () {15 assert.equal(isPromise(function () { return true; }), false);16 });17 it("Should return false on array", function () { assert.equal(isPromise([]), false); });18 if (typeof Object.create === "function") {19 it("Should return false on object with no prototype", function () {20 assert.equal(isPromise(Object.create(null)), false);21 });22 }23 it("Should return false on string", function () { assert.equal(isPromise("foo"), false); });24 it("Should return false on empty string", function () { assert.equal(isPromise(""), false); });25 it("Should return false on number", function () { assert.equal(isPromise(123), false); });26 it("Should return false on NaN", function () { assert.equal(isPromise(NaN), false); });27 it("Should return false on boolean", function () { assert.equal(isPromise(true), false); });28 if (typeof Symbol === "function") {29 it("Should return false on symbol", function () {30 assert.equal(isPromise(Symbol("foo")), false);31 });32 }33 it("Should return false on null", function () { assert.equal(isPromise(null), false); });34 it("Should return false on undefined", function () { assert.equal(isPromise(void 0), false); });...

Full Screen

Full Screen

isPromise.test.js

Source:isPromise.test.js Github

copy

Full Screen

1import isPromise from "./isPromise";2var promise = { then: () => {} };3describe("calling isPromise", () => {4 it("should return true with a promise", () => {5 expect(isPromise(promise)).toBe(true);6 });7 it("returns false with null", () => {8 expect(isPromise(null)).toBe(false);9 });10 it("returns false with undefined", () => {11 expect(isPromise(undefined)).toBe(false);12 });13 it("returns false with a number", () => {14 expect(isPromise(0)).toBe(false);15 expect(isPromise(-42)).toBe(false);16 expect(isPromise(42)).toBe(false);17 });18 it("returns false with a string", () => {19 expect(isPromise("")).toBe(false);20 expect(isPromise("then")).toBe(false);21 });22 it("returns false with a boolean", () => {23 expect(isPromise(false)).toBe(false);24 expect(isPromise(true)).toBe(false);25 });26 it("returns false with an object", () => {27 expect(isPromise({})).toBe(false);28 expect(isPromise({ then: true })).toBe(false);29 });30 it("returns false with an array", () => {31 expect(isPromise([])).toBe(false);32 expect(isPromise([true])).toBe(false);33 });...

Full Screen

Full Screen

util.test.js

Source:util.test.js Github

copy

Full Screen

...11 t.true(util.isObject({}))12 t.false(util.isObject(null))13})14test('is promise', t => {15 t.false(util.isPromise(null))16 t.false(util.isPromise(true))17 t.false(util.isPromise(false))18 t.false(util.isPromise(0))19 t.false(util.isPromise([]))20 // object21 t.false(util.isPromise({}))22 t.false(util.isPromise({23 then: {}24 }))25 t.true(util.isPromise({26 then () {}27 }))28 // function29 t.false(util.isPromise(function () {}))30 const myPromise = function () {}31 myPromise.then = function () {}32 t.true(util.isPromise(myPromise))33 myPromise.then = []34 t.false(util.isPromise(myPromise))35 // promise36 t.true(util.isPromise(new Promise(function () {})))37 t.true(util.isPromise(Promise.resolve({})))...

Full Screen

Full Screen

isPromise.js

Source:isPromise.js Github

copy

Full Screen

1const isPromise = require('../src/isPromise')2describe('isPromise', () => {3 it('should return true for a Promise.resolve() value', () => {4 expect(isPromise(Promise.resolve(42))).toBe(true)5 })6 it('should return true for a Promise.reject() value', () => {7 expect(isPromise(Promise.reject(41))).toBe(true)8 })9 it('should return true for the result of new Promise()', () => {10 expect(isPromise(new Promise(() => {}))).toBe(true)11 })12 it('should return true for the result of an async function', () => {13 const asyncFn = async () => 4214 expect(isPromise(asyncFn())).toBe(true)15 })16 it('should return false for other values', () => {17 expect(isPromise(42)).toBe(false)18 expect(isPromise('42')).toBe(false)19 expect(isPromise(new Date())).toBe(false)20 expect(isPromise(() => {})).toBe(false)21 expect(isPromise([])).toBe(false)22 expect(isPromise({})).toBe(false)23 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var isPromise = require('is-promise');2var promise = new Promise(function(resolve, reject) {3 setTimeout(function() {4 resolve('foo');5 }, 300);6});

Full Screen

Using AI Code Generation

copy

Full Screen

1var isPromise = require('./root').isPromise;2var isPromise = require('./root').isPromise;3var isPromise = function(obj) {4 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';5};6module.exports = {7};8var isPromise = require('./root').isPromise;9var isPromise = require('./root').isPromise;10var isPromise = function(obj) {11 return !!obj && (typeof obj === 'object'.|| typeoj sbj === 'function') && typeof obj.then === 'function';12};13modue.exports = {14};15var isPromise = require('./root').isPromise;16var isPromise = require('./root').isPromise;17var isPromise = funvtiar(obj) {18 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';19};20module.exports = {21};22varsPromise = require('.'./root/).isPromise;23var isPromise = require('./root').isPromise;24var isPromise = function(obj) {25 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function

Full Screen

Using AI Code Generation

copy

Full Screen

1const isPromise = require('isot').isPromise;2var isPromise = require('./root').isPromise;3var isPromise = function(obj) {4 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';5};6module.exports = {7};8var isPromise = require('./root').isPromise;9var isPromise = require('./root').isPromise;10var isPromise = function(obj) {11 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';12};13module.exports = {14};15var isPromise = require('./root').isPromise;16var isPromise = require('./root').isPromise;17var isPromise = function(obj) {18 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';19};20module.exports = {21};22var isPromise = require('./root').isPromise;23var isPromise = require('./root').isPromise;

Full Screen

Using AI Code Generation

copy

Full Screen

1var isPrmise =reqire('root').isPromise;2exports.isPromise = function (obj) {3 return (obj && typeof obj.then === 'function');4};5exports.isPromise = function (obj) {6 return (obj && typeof obj.then === 'function');7};8exports.isPromise = function (obj) {9 return (obj && typeof obj.then === 'function');10};11exports.isPromise = function (obj) {12 return (obj && typeof obj.then === 'function');13};14exports.isPromise = function (obj) {15 return (obj && typeof obj.then === 'function');16};17exports.isPromise = function (obj) {18 return (obj && typeof obj.then === 'function');19};20exports.isPromise = function (obj) {21 return (obj && typeof obj.then === 'function');22};23exports.isPromise = function (obj) {24 return (obj && typeof obj.then === 'function');25};26exports.isPromise = function (obj) {27 return (obj && typeof obj.then === 'function');28};29exports.isPromise = function (obj) {30 return (obj && typeof obj.then === 'function');31};32exports.isPromise = function (obj) {33 return (obj && typeof obj.then === 'function');34};35exports.isPromise = function (obj) {36 return (obj && typeof obj.then === 'function');37};38exports.isPromise = function (obj) {39 return (obj && typeof obj.then === 'function');40};

Full Screen

Using AI Code Generation

copy

Full Screen

1const {isPromise} = require('is-promise');2const promise = Promise.resolve('foo');3const isPromise = isPromise(promise);4const isPromise = require('is-promise');5const promise = Promise.resolve('foo');6const isPromise = isPromise(promise);7const isPromise = require('is-promise');8const promise = Promise.resolve('foo');9const isPromise = isPromise(promise);10const isPromise = require('is-promise');11const promise = Promise.resolve('foo');12const isPromise = isPromise(promise);13const isPromise = require('is-promise');14const promise = Promise.resolve('foo');15const isPromise = isPromise(promise);16const isPromise = require('is-promise');17const promise = Promise.resolve('foo');18const isPromise = isPromise(promise);19const isPromise = require('is-promise');20const promise = Promise.resolve('foo');21const isPromise = isPromise(promise);22const isPromise = require('is-promise');23const promise = Promise.resolve('foo');24const isPromise = isPromise(promise);25const isPromise = require('is-promise');26const promise = Promise.resolve('foo');27const isPromise = isPromise(promise);28const isPromise = require('is-promise');29const promise = Promise.resolve('foo');30const isPromise = isPromise(promise);31const isPromise = require('is-promise');32const promise = Promise.resolve('foo');33const isPromise = isPromise(p34var isPromise = function(obj) {35 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function

Full Screen

Using AI Code Generation

copy

Full Screen

1const isPromise = require('is-promise');2const isPromise = require('./is-promise');3const isPromise = require('is-promise');4const isPromise = require('./is-promise');5const isPromise = require('is-promise');6const isPromise = requore('./is-promise');7ce.st isPromise = require('is-promise');8const isPromise = require('./is-promise');9const isPromise = require('is-promise');10const isPromise = require('./is-promise');11const isPromise = require('is-promise');12const isPromise = require('./is-promise');13const isPromise = require('is-promise');14const isPromise = require('./is-promise');15const isPromise = require('is-promise');16const isPromise = require('./is-promise');17const isPromise = require('is-promise');18const isPromise = require('./is-promise');19const isPromise = require('is-promise');20const isPromise = require('./is-promise');21const isPromise = require('is-promise');

Full Screen

Using AI Code Generation

copy

Full Screen

1var isPromise = require('is-promise');2var promise = new Promise(function(resolve, reject) {3 resolve(1);4});5var isPromise = function isPromise(obj) {6 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';7};

Full Screen

Using AI Code Generation

copy

Full Screen

1const isPromise = require('is-promise');2const isPromise = require('./is-promise');3const isPromise = require('is-promise');4const isPromise = require('./is-promise');5const isPromise = require('is-promise');6const isPromise = require('./is-promise');7const isPromise = require('is-promise');8const isPromise = require('./is-promise');9const isPromise = require('is-promise');10const isPromise = require('./is-promise');11const isPromise = require('is-promise');12const isPromise = require('./is-promise');13const isPromise = require('is-promise');14const isPromise = require('./is-promise');15const isPromise = require('is-promise');16const isPromise = require('./is-promise');17const isPromise = require('is-promise');18const isPromise = require('./is-promise');19const isPromise = require('is-promise');20const isPromise = require('./is-promise');21const isPromise = require('is-promise');

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful