Best JavaScript code snippet using redwood
serialize_mms_agents_utils.js
Source:serialize_mms_agents_utils.js
1"use strict"2var config = require("config")3var utils = require("../lib/utils.js")4var errorLib = require("../lib/error.js")5var db = require("../lib/db.js")6var clc = require('cli-color')7var async = require("async")8var sanitizeHtml = require('sanitize-html')9var serializeUtils = require("../lib/serialize_utils.js")10require("string_score")11//builds the default object for agents based on existing mms agent data12exports.buildAgentFromMmsAgent = function(mmsAgent){13 var newAgent = {14 viaf: false,15 viafAll: [],16 registry: "temp" + Date.now() + Math.floor(Math.random() * (1000000 - 1)) + 1,17 nameControlled: false,18 wikidata: false,19 lcId: false,20 gettyId: false,21 dbpedia: false,22 birth: false,23 death: false,24 type: false,25 source: false,26 useCount: 0,27 nameNormalized: []28 }29 if (mmsAgent.viaf){30 newAgent.viaf = mmsAgent.viaf31 newAgent.viafAll = [mmsAgent.viaf]32 }else{33 newAgent.viaf = "noViaf" + Date.now() + Math.floor(Math.random() * (1000000 - 1)) + 134 }35 newAgent.nameControlled = mmsAgent.namePart36 newAgent.type = mmsAgent.type37 newAgent.nameNormalized = [utils.normalizeAndDiacritics(mmsAgent.namePart)]38 return newAgent39}40exports.populateMmsAgentsCollections = function(cb){41 db.returnCollectionRegistry("mmsCollections",function(err,mmsCollections){42 var cursor = mmsCollections.find({}, { 'agents' : 1, 'subjects' : 1 }).stream()43 var totalAgents = 0, totalAgentsWithViaf = 0, totalAgentsNotFoundInRegistry = 0, loadedAgents = 044 cursor.on('data', function(collection) {45 46 cursor.pause()47 process.stdout.cursorTo(0)48 process.stdout.write(clc.black.bgGreenBright("populateMMSAgentsCollctions | totalAgents: " + totalAgents + " totalAgentsWithViaf:" + totalAgentsWithViaf + " totalAgentsNotFoundInRegistry: " + totalAgentsNotFoundInRegistry ))49 loadedAgents = loadedAgents + collection.agents.length50 //move the name subjects into the agents for processing51 collection.subjects.forEach(function(s){52 if (s.type==='name'){53 if (s.text!=='None'||s.text!=='Unknown'||s.text.trim()!==''){ 54 collection.agents.push({55 namePart : s.text,56 type: s.nameType,57 authority: s.authority,58 valueURI: s.valueURI59 })60 61 62 }63 }64 })65 var recordAgents = JSON.parse(JSON.stringify(collection.agents))66 var recordSubjects = JSON.parse(JSON.stringify(collection.subjects))67 var updateHost = false68 async.each(collection.agents, function(agent, eachCallback) {69 70 totalAgents++71 var loc=false72 if (agent.valueURI){73 if (agent.valueURI.search("loc.gov")>-1){74 loc = agent.valueURI.split('/names/')[1]75 agent.loc = loc76 }77 }78 //if they have a loc then use that to look up in the 79 if (loc){ 80 //first get the real loc data81 serializeUtils.returnViafByLccn(loc, function(locLookup){82 totalAgentsWithViaf++83 if (locLookup){84 var viaf = locLookup._id85 agent.viaf = viaf86 //update the host record87 //we want to go back and update the orginal source record with the VIAF id88 for (var x in recordAgents){89 if (recordAgents[x].namePart===agent.namePart){90 recordAgents[x].viaf = viaf91 updateHost=true92 }93 }94 for (var x in recordSubjects){95 if (recordSubjects[x].text===agent.namePart){96 recordSubjects[x].viaf = viaf97 updateHost=true98 }99 } 100 101 serializeUtils.returnAgentByViaf(viaf,function(existingAgent){102 103 if (!existingAgent){104 var updateAgent = exports.buildAgentFromMmsAgent(agent)105 updateAgent.useCount++106 updateAgent.source = "mmsCollection" +collection._id 107 108 serializeUtils.addAgentByViaf(updateAgent,function(){109 eachCallback()110 })111 }else{112 //already in agents, it is okay113 eachCallback()114 }115 })116 }else{117 //we could not find that viaf ID, just add it by name118 serializeUtils.returnAgentByName(agent.namePart, function(existingAgent){119 if (existingAgent){120 if (existingAgent.viaf){121 if (!isNaN(existingAgent.viaf)){122 for (var x in recordAgents){123 if (recordAgents[x].namePart===agent.namePart){124 recordAgents[x].viaf = existingAgent.viaf125 updateHost=true126 }127 }128 for (var x in recordSubjects){129 if (recordSubjects[x].text===agent.namePart){130 recordSubjects[x].viaf = existingAgent.viaf131 updateHost=true132 }133 } 134 }135 136 }137 eachCallback()138 }else{139 //not yet in the agents table140 totalAgentsNotFoundInRegistry++141 var updateAgent = exports.buildAgentFromMmsAgent(agent)142 updateAgent.useCount++143 //console.log("!",updateAgent)144 updateAgent.source = "mmsCollection" +collection._id 145 serializeUtils.addAgentByName(updateAgent,function(){146 eachCallback()147 })148 }149 })150 }151 })152 }else{153 //add it by name154 serializeUtils.returnAgentByName(agent.namePart, function(existingAgent){155 if (existingAgent){156 if (existingAgent.viaf){157 if (!isNaN(existingAgent.viaf)){158 for (var x in recordAgents){159 if (recordAgents[x].namePart===agent.namePart){160 recordAgents[x].viaf = existingAgent.viaf161 updateHost=true162 }163 }164 for (var x in recordSubjects){165 if (recordSubjects[x].text===agent.namePart){166 recordSubjects[x].viaf = existingAgent.viaf167 updateHost=true168 }169 } 170 }171 172 }173 eachCallback()174 }else{175 //not yet in the agents table176 totalAgentsNotFoundInRegistry++177 var updateAgent = exports.buildAgentFromMmsAgent(agent)178 updateAgent.useCount++179 //console.log("2",updateAgent)180 updateAgent.source = "mmsCollection" +collection._id 181 serializeUtils.addAgentByName(updateAgent,function(){182 eachCallback()183 })184 }185 })186 }187 }, function(err){188 if (err) console.log(err)189 //done190 if (updateHost){191 mmsCollections.update({ _id: collection._id },{ $set: { agents: recordAgents, subjects : recordSubjects} }, function(err, result) {192 if(err) console.log(err)193 // console.log(collection._id)194 // console.log("~~~~~~~~~~~~~~~")195 // console.log(recordAgents)196 // console.log("===============")197 // console.log(recordSubjects)198 // console.log(result.result)199 cursor.resume()200 })201 }else{202 cursor.resume()203 }204 205 206 })207 })208 209 cursor.once('end', function() { 210 console.log(cursor.cursorState.documents.length)211 console.log("populateMMSAgentsCollctions - Done!\n")212 process.stdout.cursorTo(0)213 process.stdout.write(clc.black.bgGreenBright("populateMMSAgentsCollctions | totalAgents: " + totalAgents + " totalAgentsWithViaf:" + totalAgentsWithViaf + " totalAgentsNotFoundInRegistry: " + totalAgentsNotFoundInRegistry ))214 cb() 215 })216 })217}218exports.populateMmsAgentsContainers = function(cb){219 db.returnCollectionRegistry("mmsContainers",function(err,mmsContainers){220 var cursor = mmsContainers.find({}, { 'agents' : 1, 'subjects' : 1 }).stream()221 var totalAgents = 0, totalAgentsWithViaf = 0, totalAgentsNotFoundInRegistry = 0, loadedAgents = 0222 cursor.on('data', function(container) {223 224 cursor.pause()225 process.stdout.cursorTo(0)226 process.stdout.write(clc.black.bgGreenBright("populateMMSAgentsContainers | totalAgents: " + totalAgents + " totalAgentsWithViaf:" + totalAgentsWithViaf + " totalAgentsNotFoundInRegistry: " + totalAgentsNotFoundInRegistry ))227 loadedAgents = loadedAgents + container.agents.length228 //move the name subjects into the agents for processing229 container.subjects.forEach(function(s){230 if (s.type==='name'){231 if (s.text!=='None'||s.text!=='Unknown'||s.text.trim()!==''){ 232 container.agents.push({233 namePart : s.text,234 type: s.nameType,235 authority: s.authority,236 valueURI: s.valueURI237 })238 239 240 }241 }242 })243 var recordAgents = JSON.parse(JSON.stringify(container.agents))244 var recordSubjects = JSON.parse(JSON.stringify(container.subjects))245 var updateHost = false246 async.each(container.agents, function(agent, eachCallback) {247 248 totalAgents++249 var loc=false250 if (agent.valueURI){251 if (agent.valueURI.search("loc.gov")>-1){252 loc = agent.valueURI.split('/names/')[1]253 agent.loc = loc254 }255 }256 //if they have a loc then use that to look up in the 257 if (loc){ 258 //first get the real loc data259 serializeUtils.returnViafByLccn(loc, function(locLookup){260 totalAgentsWithViaf++261 if (locLookup){262 var viaf = locLookup._id263 agent.viaf = viaf264 265 //update the host record266 //we want to go back and update the orginal source record with the VIAF id267 for (var x in recordAgents){268 if (recordAgents[x].namePart===agent.namePart){269 recordAgents[x].viaf = viaf270 updateHost=true271 }272 }273 for (var x in recordSubjects){274 if (recordSubjects[x].text===agent.namePart){275 recordSubjects[x].viaf = viaf276 updateHost=true277 }278 } 279 serializeUtils.returnAgentByViaf(viaf,function(existingAgent){280 281 if (!existingAgent){282 var updateAgent = exports.buildAgentFromMmsAgent(agent)283 updateAgent.useCount++284 updateAgent.source = "mmsContainer" +container._id 285 serializeUtils.addAgentByViaf(updateAgent,function(){286 eachCallback()287 })288 }else{289 //already in agents, it is okay290 eachCallback()291 }292 })293 }else{294 //we could not find that viaf ID, just add it by name295 serializeUtils.returnAgentByName(agent.namePart, function(existingAgent){296 if (existingAgent){297 if (existingAgent.viaf){298 if (!isNaN(existingAgent.viaf)){299 for (var x in recordAgents){300 if (recordAgents[x].namePart===agent.namePart){301 recordAgents[x].viaf = existingAgent.viaf302 updateHost=true303 }304 }305 for (var x in recordSubjects){306 if (recordSubjects[x].text===agent.namePart){307 recordSubjects[x].viaf = existingAgent.viaf308 updateHost=true309 }310 } 311 }312 313 }314 eachCallback()315 }else{316 //not yet in the agents table317 totalAgentsNotFoundInRegistry++318 var updateAgent = exports.buildAgentFromMmsAgent(agent)319 updateAgent.useCount++320 //console.log("!",updateAgent)321 updateAgent.source = "mmsContainer" +container._id 322 serializeUtils.addAgentByName(updateAgent,function(){323 eachCallback()324 })325 }326 })327 }328 })329 }else{330 //add it by name331 serializeUtils.returnAgentByName(agent.namePart, function(existingAgent){332 if (existingAgent){333 if (existingAgent.viaf){334 if (!isNaN(existingAgent.viaf)){335 for (var x in recordAgents){336 if (recordAgents[x].namePart===agent.namePart){337 recordAgents[x].viaf = existingAgent.viaf338 updateHost=true339 }340 }341 for (var x in recordSubjects){342 if (recordSubjects[x].text===agent.namePart){343 recordSubjects[x].viaf = existingAgent.viaf344 updateHost=true345 }346 } 347 }348 349 }350 eachCallback()351 }else{352 //not yet in the agents table353 totalAgentsNotFoundInRegistry++354 var updateAgent = exports.buildAgentFromMmsAgent(agent)355 updateAgent.useCount++356 //console.log("2",updateAgent)357 updateAgent.source = "mmsContainer" +container._id 358 serializeUtils.addAgentByName(updateAgent,function(){359 eachCallback()360 })361 }362 })363 }364 }, function(err){365 if (err) console.log(err)366 //done367 368 if (updateHost){369 mmsContainers.update({ _id: container._id },{ $set: { agents: recordAgents, subjects : recordSubjects} }, function(err, result) {370 if(err) console.log(err)371 // console.log(container._id)372 // console.log("~~~~~~~~~~~~~~~")373 // console.log(recordAgents)374 // console.log("===============")375 // console.log(recordSubjects)376 // console.log(result.result)377 cursor.resume()378 })379 }else{380 cursor.resume()381 }382 })383 })384 385 cursor.once('end', function() { 386 console.log(cursor.cursorState.documents.length)387 console.log("populateMMSAgentsContainers - Done!\n")388 process.stdout.cursorTo(0)389 process.stdout.write(clc.black.bgGreenBright("populateMMSAgentsContainers | totalAgents: " + totalAgents + " totalAgentsWithViaf:" + totalAgentsWithViaf + " totalAgentsNotFoundInRegistry: " + totalAgentsNotFoundInRegistry ))390 cb() 391 })392 })393}394exports.populateMmsAgentsItems = function(cb){395 db.returnCollectionRegistry("mmsItems",function(err,mmsItems){396 var cursor = mmsItems.find({}, { 'agents' : 1, 'subjects' : 1 }).stream()397 var totalAgents = 0, totalAgentsWithViaf = 0, totalAgentsNotFoundInRegistry = 0, loadedAgents = 0398 cursor.on('data', function(item) {399 400 cursor.pause()401 process.stdout.cursorTo(0)402 process.stdout.write(clc.black.bgGreenBright("populateMMSAgentsItems | totalAgents: " + totalAgents + " totalAgentsWithViaf:" + totalAgentsWithViaf + " totalAgentsNotFoundInRegistry: " + totalAgentsNotFoundInRegistry ))403 loadedAgents = loadedAgents + item.agents.length404 //move the name subjects into the agents for processing405 item.subjects.forEach(function(s){406 if (s.type==='name'){407 if (s.text!=='None'||s.text!=='Unknown'||s.text.trim()!==''){ 408 item.agents.push({409 namePart : s.text,410 type: s.nameType,411 authority: s.authority,412 valueURI: s.valueURI413 })414 415 416 }417 }418 })419 var recordAgents = JSON.parse(JSON.stringify(item.agents))420 var recordSubjects = JSON.parse(JSON.stringify(item.subjects))421 var updateHost = false422 async.each(item.agents, function(agent, eachCallback) {423 424 totalAgents++425 var loc=false426 if (agent.valueURI){427 if (agent.valueURI.search("loc.gov")>-1){428 loc = agent.valueURI.split('/names/')[1]429 agent.loc = loc430 }431 }432 //if they have a loc then use that to look up in the 433 if (loc){ 434 //first get the real loc data435 serializeUtils.returnViafByLccn(loc, function(locLookup){436 totalAgentsWithViaf++437 if (locLookup){438 var viaf = locLookup._id439 agent.viaf = viaf440 //update the host record441 //we want to go back and update the orginal source record with the VIAF id442 for (var x in recordAgents){443 if (recordAgents[x].namePart===agent.namePart){444 recordAgents[x].viaf = viaf445 updateHost=true446 }447 }448 for (var x in recordSubjects){449 if (recordSubjects[x].text===agent.namePart){450 recordSubjects[x].viaf = viaf451 updateHost=true452 }453 } 454 455 serializeUtils.returnAgentByViaf(viaf,function(existingAgent){456 457 if (!existingAgent){458 var updateAgent = exports.buildAgentFromMmsAgent(agent)459 updateAgent.useCount++460 updateAgent.source = "mmsItem" +item._id 461 serializeUtils.addAgentByViaf(updateAgent,function(){462 eachCallback()463 })464 }else{465 //already in agents, it is okay466 eachCallback()467 }468 })469 }else{470 //we could not find that viaf ID, just add it by name471 serializeUtils.returnAgentByName(agent.namePart, function(existingAgent){472 if (existingAgent){473 if (existingAgent.viaf){474 if (!isNaN(existingAgent.viaf)){475 for (var x in recordAgents){476 if (recordAgents[x].namePart===agent.namePart){477 recordAgents[x].viaf = existingAgent.viaf478 updateHost=true479 }480 }481 for (var x in recordSubjects){482 if (recordSubjects[x].text===agent.namePart){483 recordSubjects[x].viaf = existingAgent.viaf484 updateHost=true485 }486 } 487 }488 489 }490 eachCallback()491 }else{492 //not yet in the agents table493 totalAgentsNotFoundInRegistry++494 var updateAgent = exports.buildAgentFromMmsAgent(agent)495 updateAgent.useCount++496 //console.log("!",updateAgent)497 updateAgent.source = "mmsItem" +item._id 498 serializeUtils.addAgentByName(updateAgent,function(){499 eachCallback()500 })501 }502 })503 }504 })505 }else{506 //add it by name507 serializeUtils.returnAgentByName(agent.namePart, function(existingAgent){508 if (existingAgent){509 if (existingAgent.viaf){510 if (!isNaN(existingAgent.viaf)){511 for (var x in recordAgents){512 if (recordAgents[x].namePart===agent.namePart){513 recordAgents[x].viaf = existingAgent.viaf514 updateHost=true515 }516 }517 for (var x in recordSubjects){518 if (recordSubjects[x].text===agent.namePart){519 recordSubjects[x].viaf = existingAgent.viaf520 updateHost=true521 }522 } 523 }524 525 }526 eachCallback()527 }else{528 //not yet in the agents table529 totalAgentsNotFoundInRegistry++530 var updateAgent = exports.buildAgentFromMmsAgent(agent)531 updateAgent.useCount++532 533 updateAgent.source = "mmsItem" +item._id 534 //console.log("2",updateAgent)535 serializeUtils.addAgentByName(updateAgent,function(){536 eachCallback()537 })538 }539 })540 }541 }, function(err){542 if (err) console.log(err)543 //done544 545 if (updateHost){546 mmsItems.update({ _id: item._id },{ $set: { agents: recordAgents, subjects : recordSubjects} }, function(err, result) {547 if(err) console.log(err)548 // console.log(item._id)549 // console.log("~~~~~~~~~~~~~~~")550 // console.log(recordAgents)551 // console.log("===============")552 // console.log(recordSubjects)553 // console.log(result.result)554 cursor.resume()555 })556 }else{557 cursor.resume()558 }559 })560 })561 562 cursor.once('end', function() { 563 console.log(cursor.cursorState.documents.length)564 console.log("populateMMSAgentsItems - Done!\n")565 process.stdout.cursorTo(0)566 process.stdout.write(clc.black.bgGreenBright("populateMMSAgentsItems | totalAgents: " + totalAgents + " totalAgentsWithViaf:" + totalAgentsWithViaf + " totalAgentsNotFoundInRegistry: " + totalAgentsNotFoundInRegistry ))567 cb() 568 })569 })...
agent.js
Source:agent.js
1var express = require('express');2var router = express.Router();3var bcrypt = require('bcryptjs');4const passport = require('passport');5const flash=require('connect-flash');6const multer = require('multer');7const path = require('path');8var Agent=require('../modules/agent')9var Property=require('../modules/property')10/**11 -------------------------------------12 ++++++> CONFIG ['muter'] <++++++++13 -------------------------------------14**/15var storage=multer.diskStorage({16 destination:'./public/uploads/images',17 filename:function(req,file,cb){18 cb(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname));19 }20});21var upload=multer({storage:storage}).any('property_images');22var uploadUpdate=multer({storage:storage}).single('company-logo');23/**24 -------------------------------------25 ++++++> GET REQUESTS <++++++++26 -------------------------------------27**/28/* GET agent register page. */29router.get('/logout',function(req,res,next){30 req.logout();31 res.redirect('login');32});33/* GET agent register page. */34router.get('/register',notLoggedIn, function(req, res, next) {35 /**36 *37 let newAgent=new Agent({38 firstname:'shelt',39 lastname:'shelt',40 company:'shelt',41 username:'admin_emmer',42 email:'shelt@gmail.com',43 phone_number:'080SHELTHOT',44 password:'$2a$10$y7.3KeNZQCTVNXTqnj9QQuuZjHQ./wWBkX/.AZGkiuLTSeKsrNUpe',45 location:'Lagos',46 address:'No 61 ikeja Lagos',47 profile_image:'shelt.logo.png',48 auth:true,49 diskSpace:'unlimited',50 activate:true,51 hash:"shelter_hashing_$2a$10$y7.3KeNZQCTVNXTqnj9QQuuZjHQ./wWBkX/.AZGkiuLTSeKsrNUpe"52 });53 newAgent.save(function (err) {54 if (err) {55 console.log(err);56 }else {57 console.log(newAgent);58 }59 })60 */61 res.render('agent/register');62});63/* GET agent login page. */64router.get('/login',notLoggedIn, function(req, res, next) {65 var message=req.flash('error');66 res.render('agent/login',{67 //csrfToken:req.csrfToken(),68 error:message,69 hasError:message.length > 070 });71});72/* GET agent dashboard page. */73router.get('/dashboard',isLoggedIn, function(req, res, next) {74 Property.find({property_agent_id:req.user.id},function (err,property) {75 var count=property.length;76 var agent=req.user;77 if (count >=agent.diskSpace) {78 var isMemory=false;79 }else {80 var isMemory=true;81 }82 console.log(req.user,"user");83 res.render('agent/dashboard',{properties:property,isMemory:isMemory});84 })85});86/**87 -------------------------------------88 ++++++> POST REQUESTS <++++++++89 -------------------------------------90**/91router.post('/register', function(req, res, next) {92 const firstname=req.body.firstname;93 const lastname=req.body.lastname;94 const company=req.body.company;95 const username=req.body.username;96 const address=req.body.address;97 const email=req.body.email;98 const phone_number=req.body.phone_number;99 const location=req.body.location;100 const password=req.body.password;101 const confirm_password=req.body.confirm_password;102 req.checkBody('firstname','firstname is required').notEmpty();103 req.checkBody('lastname','lastname is required').notEmpty();104 req.checkBody('company','company name is required').notEmpty();105 req.checkBody('username','username is required').notEmpty();106 req.checkBody('address','address is required').notEmpty();107 req.checkBody('email','email is required').notEmpty();108 req.checkBody('email','email is not valid').isEmail();109 req.checkBody('location','location is required').notEmpty();110 req.checkBody('phone_number','phoneNo is required').notEmpty();111 req.checkBody('password','password is required').notEmpty();112 req.checkBody('confirm_password','password do not match').equals(password);113 let error=req.validationErrors();114 if (error) {115 res.send({error:error});116 }117 else{118 Agent.findOne({119 $or:[120 {"username":username},{"email":email}121 ]},function(err,agent) {122 if (agent) {123 if (agent.username == username) {124 res.send({error:`username <b>${username}</b> has been taken`,state:'error'});125 }else {126 res.send({error:`email <b>${email}</b> has been taken`,state:'error'});127 }128 }129 else{130 let newAgent=new Agent({131 firstname:firstname,132 lastname:lastname,133 company:company,134 username:username,135 address:address,136 email:email,137 phone_number:phone_number,138 password:password,139 location:location,140 });141 bcrypt.genSalt(10,function(err,salt){142 bcrypt.hash(newAgent.password,salt,function(err,hashPass) {143 if (err) {144 console.log(err);145 }146 bcrypt.hash('shelter_hashing',salt,function(err,hash) {147 if (err) {148 console.log(err);149 }150 newAgent.password=hashPass;151 newAgent.hash=hash152 newAgent.save(function(err) {153 if (err) {154 console.log(err);155 }156 else{157 res.send({state:'success'});158 }159 })160 })161 })162 })163 }164 })165 }166});167 router.post("/login",function(req,res,next){168 passport.authenticate('local.agent',{169 successRedirect:'/agent/dashboard',170 failureRedirect:'/agent/login',171 failureFlash:true172 })(req,res,next);173 });174/* POST property */175router.post('/property',function(req,res){176 upload(req,res,function(err) {177 if (err) {178 console.log(err);179 }180 else {181 var property_title=req.body.property_title;182 var property_details=req.body.property_details;183 var property_features=req.body.property_features;184 var property_price=req.body.property_price;185 var property_location=req.body.property_location;186 var property_address=req.body.property_address;187 var property_category=req.body.property_category;188 var property_agent_id=req.body.property_agent_id;189 var special_product=req.body.special_product;190 var special_rate=req.body.special_rate;191 var property_duration=req.body.property_duration;192 var property_agent_id=req.body.property_agent_id;193 var property_images=req.files;194 req.checkBody('property_title','property title is required').notEmpty();195 req.checkBody('property_duration','property duration is required').notEmpty();196 req.checkBody('property_details','property details is required').notEmpty();197 req.checkBody('property_features','property features is required').notEmpty();198 req.checkBody('property_price','property price is required').notEmpty();199 req.checkBody('property_location','property location is required').notEmpty();200 req.checkBody('property_address','property address is required').notEmpty();201 req.checkBody('property_category','property category is required').notEmpty();202 let error=req.validationErrors();203 if (error) {204 res.send({error:error})205 console.log(error);206 return false207 }else{208 var images=[];209 for (var i = 0; i < property_images.length; i++) {210 newImages=property_images[i].filename211 images.push(newImages)212 };213 var property_features=property_features.split(',')214 //** genrated a random refrence number **//215 var ref_number=Math.floor(Math.random(1000) * 100000)216 var newProperty=new Property({217 property_title:property_title,218 property_details:property_details,219 property_features:property_features,220 property_location:property_location,221 property_address:property_address,222 property_category:property_category,223 property_price:property_price,224 special_rate:special_rate,225 special_product:special_product,226 duration:property_duration,227 property_agent_id:property_agent_id,228 property_images:images,229 ref_number:ref_number230 })231 newProperty.save(function(err,property) {232 if (err) {233 console.log(err)234 }235 else{236 console.log(property);237 res.send({success:true})238 }239 })240 }241}242});243});244router.post("/update",function(req,res) {245 uploadUpdate(req,res,function(err) {246 if (err) {247 console.log(err);248 }249 else {250 var updateAgent={}251 var id=req.body.agent_id252 if (req.file===undefined) {253 updateAgent.fullname=req.body.fullname;254 updateAgent.username=req.body.username;255 updateAgent.company=req.body.company256 updateAgent.phone_number=req.body.phone_number257 updateAgent.location=req.body.location258 }else {259 updateAgent.fullname=req.body.fullname;260 updateAgent.username=req.body.username;261 updateAgent.company=req.body.company262 updateAgent.phone_number=req.body.phone_number263 updateAgent.location=req.body.location264 updateAgent.profile_image=req.file.filename265 }266 let query={_id:id}267 Agent.update(query,updateAgent,function(err,agent) {268 if (err) {269 console.log(err);270 }else {271 req.flash('success',"Account was successfully updated")272 res.redirect('/agent/dashboard')273 }274 })275 }276})277})278router.get('/subscribe',function(req,res) {279 res.render('agent/subscribe')280})281router.get('/:id', function(req, res, next) {282 Agent.findById(req.params.id)283 .exec(function(err,agent) {284 console.log(agent);285 res.render('agent/agent', { agentInfo:agent });286 })287});288module.exports = router;289/**290 -------------------------------------291 ++++++> HELPER FUNCTIONS <++++++++292 -------------------------------------293**/294function isLoggedIn(req,res,next){295 if(req.isAuthenticated()){296 return next();297 }298 res.redirect('/')299 }300 function notLoggedIn(req,res,next){301 if(!req.isAuthenticated()){302 return next();303 }304 var error=req.flash('danger','Your access to ths page has been denied')305 res.redirect('/')...
agents.js
Source:agents.js
1const express = require('express');2const router = express.Router();3const agents = require('../../public/Agents');4// Return List of all Agents5router.get('/', (req, res) => {6 res.json(agents);7});8// Retrieve all Agent Details by agent's INT ID9router.get('/:_id', (req, res) => {10 const found = agents.some(agent => agent._id === parseInt(req.params._id));11 if (found){12 res.json(agents.filter(agent => agent._id === parseInt(req.params._id))); 13 }14 else {15 res.status(400).json({ msg: `No agent with the id of ${req.params._id}`});16 }17});18// Ability to Add New Agent19router.post('/', (req, res) => {20 const newAgent = {21 _id: Math.floor(Math.random()*(999-100+1)+100), 22 name: req.body.name,23 address: req.body.address,24 city: req.body.city,25 state: req.body.state,26 zipCode: req.body.zipCode,27 tier: req.body.tier,28 phone:{29 primary: req.body.phone.primary,30 mobile: req.body.phone.mobile31 }32 }33 if (34 !newAgent ||35 !newAgent.address ||36 !newAgent.name ||37 !newAgent.city ||38 !newAgent.phone ||39 !newAgent.zipCode ||40 !newAgent.tier ||41 !newAgent.state42 ) {43 return res44 .status(400)45 .json({46 msg: "Please include all of the necessary fields for a new agent",47 });48 }49 agents.push(newAgent);50 res.json(agents);51})52// Update Any/All Fields by Agentâs INT ID53router.put('/:_id', (req, res) => {54 const found = agents.some(agent => agent._id === parseInt(req.params._id));55 if (found){56 const updateAgent = req.body;57 agents.forEach(agent => {58 59 if (agent._id === parseInt(req.params._id)){60 agent.name = updateAgent.name ? updateAgent.name : agent.name;61 agent.address = updateAgent.address ? updateAgent.address : agent.address;62 agent.city = updateAgent.city ? updateAgent.city : agent.city;63 agent.state = updateAgent.state ? updateAgent.state : agent.state;64 agent.zipCode = updateAgent.zipCode ? updateAgent.zipCode : agent.zipCode;65 agent.tier = updateAgent.tier ? updateAgent.tier : agent.tier;66 agent.phone = updateAgent.phone ? updateAgent.phone : agent.phone67 res.json({ msg: "Agent has been updated.", agent})68 }69 })70 }71 else {72 res.status(400).json({ msg: `No agent with the id of ${req.params._id}`});73 }74});...
Using AI Code Generation
1var redwood = require('redwoodhq');2var rw = new redwood.Redwood();3rw.setProjectName("Test Project");4rw.setTestPlanName("Test Plan");5rw.setTestCaseName("Test Case");6rw.setTestCaseId("TC001");7rw.setTestStepId("TS001");8rw.setAgentName("agent1");9rw.setAgentId("agent1");10rw.setAgentStatus("busy");11rw.setAgentIp("
Using AI Code Generation
1var rwhq = require('node-redwood');2var username = "admin";3var password = "admin";4var agentName = "test";5var agentDescription = "test agent";6var agentPlatform = "android";7var agentPlatformVersion = "7.0";8var agentDeviceName = "test";9var agentDeviceId = "test";10var agentAppPackage = "test";11var agentAppActivity = "test";12var agentAppWaitActivity = "test";13var agentAppWaitPackage = "test";14var agentAutomationName = "test";15var agentApp = "test";16var agentAppiumVersion = "test";17var agentBrowserName = "test";18var agentNewCommandTimeout = "test";19var agentPlatformName = "test";20var agentPlatformVersion = "test";21var agentDeviceName = "test";22var agentDeviceId = "test";23var agentAppPackage = "test";24var agentAppActivity = "test";25var agentAppWaitActivity = "test";26var agentAppWaitPackage = "test";27var agentAutomationName = "test";28var agentApp = "test";29var agentAppiumVersion = "test";30var agentBrowserName = "test";31var agentNewCommandTimeout = "test";32var agentPlatformName = "test";33var agentPlatformVersion = "test";
Using AI Code Generation
1var redwood = require('redwoodhq');2var agent = new redwood.Agent("agentId", "agentKey");3agent.updateAgent("agentName", "agentDescription", "agentType", "agentStatus", "agentEnvironment", "agentOS", "agentOSVersion", "agentBrowser", "agentBrowserVersion", "agentDevice", "agentDeviceVersion", "agentLocation", "agentLocationLat", "agentLocationLong", "agentCustom1", "agentCustom2", "agentCustom3", "agentCustom4", "agentCustom5", "agentCustom6", "agentCustom7", "agentCustom8", "agentCustom9", "agentCustom10", "agentCustom11", "agentCustom12", "agentCustom13", "agentCustom14", "agentCustom15", "agentCustom16", "agentCustom17", "agentCustom18", "agentCustom19", "agentCustom20", "agentCustom21", "agentCustom22", "agentCustom23", "agentCustom24", "agentCustom25", "agentCustom26", "agentCustom27", "agentCustom28", "agentCustom29", "agentCustom30", "agentCustom31", "agentCustom32", "agentCustom33", "agentCustom34", "agentCustom35", "agentCustom36", "agentCustom37", "agentCustom38", "agentCustom39", "agentCustom40", "agentCustom41", "agentCustom42", "agentCustom43", "agentCustom44", "agentCustom45", "agentCustom46", "agentCustom47", "agentCustom48", "agentCustom49", "agentCustom50", function (err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10var redwood = require('redwoodhq');11var agent = new redwood.Agent("agentId", "agentKey");12agent.updateAgentStatus("agentStatus", "agentCustom1", "agentCustom2", "agentCustom3", "agentCustom4", "agentCustom5", "agentCustom6", "agentCustom7", "agentCustom8", "agentCustom9", "agentCustom10", "agentCustom11", "agentCustom12
Using AI Code Generation
1var redwood = require("redwoodhq");2redwood.updateAgent("testAgent","testAgent1");3### 4. deleteAgent(agentName)4var redwood = require("redwoodhq");5redwood.deleteAgent("testAgent");6### 5. getAgent(agentName)7var redwood = require("redwoodhq");8redwood.getAgent("testAgent");9### 6. listAgents()10var redwood = require("redwoodhq");11redwood.listAgents();12### 7. createIntent(agentName,intentName)13var redwood = require("redwoodhq");14redwood.createIntent("testAgent","testIntent");15### 8. updateIntent(agentName,intentName,intentNewName)16var redwood = require("redwoodhq");17redwood.updateIntent("testAgent","testIntent","testIntent1");18### 9. deleteIntent(agentName,intentName)19var redwood = require("redwoodhq");20redwood.deleteIntent("testAgent","testIntent");21### 10. getIntent(agentName,intentName)22var redwood = require("redwoodhq");23redwood.getIntent("testAgent","testIntent");24### 11. listIntents(agentName)
Using AI Code Generation
1var redwood = require("redwoodhq");2var agentDetails = {3}4redwood.updateAgent("5d2f2c7e1a0b8f2b8c6b9f7d", agentDetails, function (error, response, body) {5 console.log(body);6});7var redwood = require("redwoodhq");8redwood.getAgent("5d2f2c7e1a0b8f2b8c6b9f7d", function (error, response, body) {9 console.log(body);10});11var redwood = require("redwoodhq");12redwood.getAgents(function (error, response, body) {13 console.log(body);14});15var redwood = require("redwoodhq");16redwood.getAgentsByProjectId("5d2f2c7e1a0b8f2b8c6b9f7d", function (error, response, body) {17 console.log(body);18});
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!!