Best JavaScript code snippet using wpt
worker.js
Source:worker.js
1const url = require('url');2const http = require('http');3const https = require('https');4const _data = require('./data.js');5const helpers = require('./helpers');6const _logs = require('./log');7const util = require('util');8const debug = util.debuglog('worker');9// debug logs will appear only when we debug in worker node10// NODE_DEBUG=worker node index.js11// Instantiate the worker object12var worker = {};13// timer to execute the worker process once per minute14worker.loop = () => {15 setInterval(() => {16 worker.gatherAllChecks();17 }, 1000 * 60);18};19// lookup the check data and send to validate function20worker.gatherAllChecks = () => {21 // get all the checks 22 _data.list('checks', (error, checks) => {23 if(!error && checks && checks.length > 0){24 checks.forEach(check => {25 // read in the check data26 _data.read('checks', check, (error, checkData) => {27 if(!error && checkData) {28 // validate the check data29 worker.validateCheckData(checkData);30 }else {31 debug('Error : failed to read check data - ',error);32 }33 });34 });35 }else {36 debug('Error : failed to find any checks to process - ',error);37 }38 });39};40// sanity check/ validation for the check data41worker.validateCheckData = (checkData) => {42 checkData = typeof(checkData) == 'object' && checkData !== null ? checkData : {};43 checkData.id = typeof(checkData.id) == 'string' && checkData.id.trim().length == 20 ? checkData.id.trim() : false;44 checkData.userPhone = typeof(checkData.userPhone) == 'string' && checkData.userPhone.trim().length == 10 ? checkData.userPhone.trim() : false;45 checkData.protocol = typeof(checkData.protocol) == 'string' && ['http','https'].indexOf(checkData.protocol) > -1 ? checkData.protocol : false;46 checkData.url = typeof(checkData.url) == 'string' && checkData.url.trim().length > 0 ? checkData.url.trim() : false;47 checkData.method = typeof(checkData.method) == 'string' && ['post','get','put','delete'].indexOf(checkData.method) > -1 ? checkData.method : false;48 checkData.successCodes = typeof(checkData.successCodes) == 'object' && checkData.successCodes instanceof Array && checkData.successCodes.length > 0? checkData.successCodes : false;49 checkData.timeoutSeconds = typeof(checkData.timeoutSeconds) === 'number' && checkData.timeoutSeconds % 1 === 0 && checkData.timeoutSeconds >= 1 && checkData.timeoutSeconds <= 5 ? checkData.timeoutSeconds : false;50 // may not be set : for first time checked data51 checkData.state = typeof(checkData.state) == 'string' && ['up','down'].indexOf(checkData.state) > -1 ? checkData.state : 'down' ;52 53 checkData.lastChecked = typeof(checkData.lastChecked) == 'number' && checkData.lastChecked > 0 ? checkData.lastChecked : false ;54 // if all the checks passed then pass the checks to the next step of the process55 if( checkData.id && checkData.userPhone && checkData.protocol && checkData.url &&56 checkData.method && checkData.successCodes && checkData.timeoutSeconds ){57 // perform check on check data of valid58 worker.performCheck(checkData);59 }else {60 debug('Error : check data isn\'t properly formatted. Skipping check validation');61 }62};63// perform the check 64worker.performCheck = (checkData) => {65 // prepare initial check outcome66 var checkOutcome = {67 'error' : false,68 'responseCode' : false69 };70 var outcomeSent = false;71 // parse the hostname and path out the original check data72 var parseUrl = url.parse(checkData.protocol+'://'+checkData.url, true);73 var hostname = parseUrl.hostname;74 var path = parseUrl.path;75 // construct the url76 var requestDetails = {77 'protocol' : checkData.protocol+':',78 'hostname' : hostname,79 'method' : checkData.method.toUpperCase(),80 'path' : path,81 'timeout' : checkData.timeoutSeconds * 100082 };83 // Instantiate the request object84 var _moduleToUse = checkData.protocol == 'http' ? http : https;85 var req = _moduleToUse.request(requestDetails, (res) => {86 var status = res.statusCode;87 // update checkout 88 checkOutcome.responseCode = status;89 if(!outcomeSent) {90 worker.performCheckOutcome(checkData, checkOutcome);91 outcomeSent = true;92 }93 });94 // bind to the error95 req.on('error', (error) => {96 // update checkOutcome and pass data along97 checkOutcome.error = {98 'error' : true,99 'value' : error100 };101 if(!outcomeSent) {102 worker.performCheckOutcome(checkData, checkOutcome);103 outcomeSent = true;104 }105 });106 // bind to the timeout event107 req.on('timeout', (error) => {108 // update checkOutcome and pass data along109 checkOutcome.error = {110 'error' : true,111 'value' : 'timeout'112 };113 if(!outcomeSent) {114 worker.performCheckOutcome(checkData, checkOutcome);115 outcomeSent = true;116 }117 });118 // end the request119 req.end();120};121// process check data, update check data as needed, trigger an alert if required122// special logic for handling the check that has been never checked before123worker.performCheckOutcome = (checkData, checkOutcome) => {124 var state = !checkOutcome.error && checkOutcome.responseCode && checkData.successCodes.indexOf(checkOutcome.responseCode) > -1 ? 'up' : 'down';125 // decide if alert is required126 var alertRequired = checkData.lastChecked && checkData.state !== state ? true : false;127 var timeOfCheck = Date.now();128 // log the processed data so far129 worker.log(checkData, checkOutcome, state, alertRequired, timeOfCheck);130 // update the check data131 var newCheckData = checkData;132 newCheckData.state = state;133 newCheckData.lastChecked = timeOfCheck;134 // save the updates 135 _data.update('checks', newCheckData.id, newCheckData, (error) => {136 if(!error) {137 // send alert if required138 if(alertRequired){139 worker.alertUserForStatusChange(newCheckData);140 }else {141 debug('Check outcome not changed, alert not required');142 }143 }else {144 debug('Error : failed while saving the check updates - ',error);145 }146 });147};148// send sms later using the twilio api configured149worker.alertUserForStatusChange = (newCheckData) => {150 var msg = 'Alert : Your check for '+newCheckData.method.toUpperCase()151 +' '+newCheckData.protocol+'://'+newCheckData.url+' is currently '+newCheckData.state;152 helpers.sendTwilioSMS(newCheckData.userPhone, msg, (error) => {153 if(!error){154 debug('Success : user was alerted for status change');155 }else {156 debug('Error : failed to send SMS alert who has state change - ',error);157 }158 }); 159};160// logging the required data161worker.log = (checkData, checkOutcome, state, alertRequired, timeOfCheck) => {162 var logData = {163 'check' : checkData,164 'outcome' : checkOutcome,165 'state' : state,166 'alert' : alertRequired,167 'time' : timeOfCheck168 };169 // convert data to string170 var logString = JSON.stringify(logData);171 // set name of logfile172 var logFileName = checkData.id;173 // append log string to file174 _logs.append(logFileName, logString, (error) => {175 if(error) {176 debug('Successfully logged data in logfile');177 }else {178 debug('Error : failed to append logs in logfile - ',error);179 }180 });181};182// compress the logs183worker.rotateLogs = () => {184 // list all the non-compressed log files185 _logs.list(false, (error, logs) => {186 if(!error && logs && logs.length > 0){187 logs.forEach((logfile) => {188 // compress the data to the different file189 var logId = logfile.replace('.log','');190 var newFileId = logId+'-'+Date.now();191 _logs.compress(logId, newFileId, (error) => {192 if(!error) {193 // truncate the log file194 _logs.truncate(logId, (error) => {195 if(!error) {196 debug('Success truncating log file');197 }else {198 debug('Error : failed to truncate the log file - ',error);199 }200 });201 }else { 202 debug('Error : failed to compress the log files - ',error);203 }204 });205 });206 }else {207 debug('Error : could not find any uncompressed logs - ',error);208 }209 });210};211// start the loop that compresses the logs212worker.logRotationLoop = () => {213 setInterval(() => {214 worker.rotateLogs();215 }, 1000 * 60 * 60 * 24);216};217// Init the workker script218worker.init = () => {219 // first parameter in console.log() is for color settings220 console.log('\x1b[33m%s\x1b[0m', 'Background workers are running');221 // Execute all the checks immediatly222 worker.gatherAllChecks();223 // call the loop se checks will execute later 224 worker.loop();225 // compress all the logs226 worker.rotateLogs();227 // call the compression loop, so logs will be compressed later on228 worker.logRotationLoop();229};230// Export the worker api...
workers.js
Source:workers.js
1// These are worker related tasks2// Dependencies3var path = require("path");4var fs = require("fs");5var _data = require("./data");6var helpers = require("./helpers");7var http = require("http");8var https = require("https");9var url = require("url");10var _logs = require("./logs")11var workers = {}12// alert user by sms13workers.alertUser = function(checkData) {14 var message = `Alert: Your check for ${checkData.method.toUpperCase()} ${checkData.protocol}://${checkData.url} is currently ${checkData.state}`;15 helpers.sendTwilioSms(checkData.phone, message, function(err) {16 if(!err) {17 console.log('Success: User was alerted to a status change', message)18 }else {19 console.log("Error sending sms to user: "+checkData.phone)20 }21 })22}23// Perform check and send original validated checkData to the next process24workers.performCheck = function(originalCheckData) {25 // Prepare initial check outcome for this check26 var checkOutcome = {27 'error': false,28 'responseCode': false29 }30 // Mark that the outcome has not been sent yet31 var outcomeSent = false32 // parse hostname and path out of originalCheckData33 var parsedUrl = url.parse(originalCheckData.protocol+"://"+originalCheckData.url, true);34 var hostname = parsedUrl.hostname;35 var path = parsedUrl.path;36 // construct request37 var requestDetails = {38 'protocol': originalCheckData.protocol+":",39 'hostname': hostname,40 'method': originalCheckData.method.toUpperCase(),41 'path': path,42 'timeout': originalCheckData.timeoutSeconds * 100043 };44 // instantiate request object using users selected protocol45 var _protocolModule = originalCheckData.protocol == "http" ? http : https;46 var req = _protocolModule.request(requestDetails, function(res) {47 // update checkOutcome48 checkOutcome.responseCode = res.statusCode;49 if(!outcomeSent) {50 workers.processCheckOutcome(originalCheckData, checkOutcome);51 outcomeSent = true;52 }53 });54 // Bind to the error event so it doesnt get thrown55 req.on('error', function(e) {56 checkOutcome.error = {57 'error': true,58 'value': e59 };60 if(!outcomeSent) {61 workers.processCheckOutcome(originalCheckData, checkOutcome);62 outcomeSent = true;63 }64 });65 // Bind to the timeout66 req.on('timeout', function(e) {67 checkOutcome.error = {68 'error': true,69 'value': 'timeout'70 };71 if(!outcomeSent) {72 workers.processCheckOutcome(originalCheckData, checkOutcome);73 outcomeSent = true;74 }75 });76 req.end();77}78// process checkOutcome update checkData as needed79workers.processCheckOutcome = function(originalCheckData, checkOutcome) {80 // Decide if check is up or down81 var state = !checkOutcome.error && checkOutcome.responseCode && originalCheckData.successCodes.indexOf(checkOutcome.responseCode) > -1 ? 'up' : 'down';82 // check if theres a need to alert user83 var needsAlert = originalCheckData.lastChecked && originalCheckData.state !== state ? true : false84 var timeOfCheck = Date.now();85 // update checkData86 var newCheckData = originalCheckData;87 newCheckData.state = state;88 newCheckData.lastChecked = Date.now();89 // log here90 workers.log(originalCheckData, checkOutcome, state, needsAlert, timeOfCheck)91 // Save updated data92 _data.update('checks', newCheckData.id, newCheckData, function(err) {93 if(!err) {94 if(needsAlert) {95 workers.alertUser(newCheckData)96 }else {97 console.log("Check outcome has not changed no alert needed")98 }99 }else {100 console.log("Error trying to save updates to check: "+originalCheckData.id)101 }102 })103}104workers.gatherAllChecks = function() {105 _data.list("checks", function(err, checks) {106 if(!err && checks && checks.length > 0) {107 checks.forEach(function(check) {108 // get the original check data109 _data.read("checks", check, function(err, originalCheckData) {110 if(!err && originalCheckData) {111 workers.validateCheckData(originalCheckData);112 }else {113 console.log("Error reading one of the checks data")114 }115 })116 })117 }else {118 console.log("Error: Could not find any checks to process")119 }120 })121}122workers.validateCheckData = function(checkData) {123 console.log(typeof(checkData.userPhone) == "number")124 var checkData = typeof(checkData) == 'object' && checkData != null ? checkData : {};125 checkData.id = typeof(checkData.id) == "string" && checkData.id.trim().length == 20 ? checkData.id.trim() : false126 checkData.userPhone = typeof(parseInt(checkData.userPhone)) == "number" && checkData.userPhone.trim().length == 11 ? checkData.userPhone.trim() : false;127 checkData.protocol = typeof(checkData.protocol) == "string" && ['http', 'https'].indexOf(checkData.protocol) > -1 ? checkData.protocol : false;128 checkData.url = typeof(checkData.url) == "string" && checkData.url.trim().length > 0 ? checkData.url.trim() : false;129 checkData.method = typeof(checkData.method) == "string" && ['post', 'get', 'put', 'delete'].indexOf(checkData.method) > -1 ? checkData.method : false;130 checkData.successCodes = typeof(checkData.successCodes) == "object" && checkData.successCodes instanceof Array && checkData.successCodes.length > 0 ? checkData.successCodes : false;131 checkData.timeoutSeconds = typeof(checkData.timeoutSeconds) == "number" && checkData.timeoutSeconds >= 1 && checkData.timeoutSeconds <= 5 ? checkData.timeoutSeconds : false;132 // set keys that may not be set if workers have not seen this check before []133 checkData.state = typeof(checkData.state) == "string" && ['up', 'down'].indexOf(checkData.state) > -1 ? checkData.state : 'down';134 checkData.lastChecked = typeof(checkData.lastChecked) == "number" && checkData.lastChecked > 0 ? checkData.lastChecked : false;135 // if all checks pass136 if(checkData.id &&137 checkData.userPhone &&138 checkData.protocol &&139 checkData.url &&140 checkData.method &&141 checkData.successCodes &&142 checkData.timeoutSeconds143 ) {144 workers.performCheck(checkData)145 }else {146 console.log("Error: One of the checks is not properly formatted. Skipping it >>>> ;)")147 // console.log(checkData)148 }149}150workers.log = function(originalCheckData, checkOutcome, state, needsAlert, timeOfCheck) {151 // form log data152 var logData = {153 'check': originalCheckData,154 'outcome': checkOutcome,155 'state': state,156 'alert': needsAlert,157 'time': timeOfCheck158 }159 logData = JSON.stringify(logData)160 var logFileName = originalCheckData.id161 _logs.append(logFileName, logData, function(err) {162 if(!err) {163 console.log("Logging to file successful")164 }else {165 console.log("Logging to file failed")166 }167 })168}169// timer to execute worker process once per minute170workers.loop = function() {171 setInterval(function() {172 workers.gatherAllChecks();173 }, 1000 * 60) // run every 6 minutes174}175workers.rotateLogs = function() {176 // list all none compressed logged files177 _logs.list(false, function(err, logs) {178 if(!err && logs && logs.length > 0) {179 logs.forEach(function(logFile) {180 // Compress the data to different file181 var logId = logFile.replace('.log', '');182 var newFileId = `${logId}-${new Date().getFullYear()}-${new Date().getMonth()}-${new Date().getDate()}-${new Date().getMinutes()}-${new Date().getSeconds()}`183 _logs.compress(logId, newFileId, function(err) {184 if(!err) {185 // Truncate log186 _logs.truncate(logId, function(err) {187 if(!err) {188 console.log("Success truncating logFile")189 }else {190 console.log("Error truncating logFile")191 }192 })193 }else {194 console.log("Error compressing one of the logs", err)195 }196 })197 })198 }else {199 console.log("Error: could not find any logs to rotate")200 }201 })202}203// timer to execute logs-rotation once per day204workers.logRotationLoop = function() {205 setInterval(function () {206 workers.rotateLogs()207 }, 1000 * 10)208}209// init logic210workers.init = function() {211 // Execute all checks212 workers.gatherAllChecks()213 // call loop to run all checks214 workers.loop();215 // compress logs216 workers.rotateLogs();217 // call compression loop218 workers.logRotationLoop();219}...
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.checkData('testId', function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7var WebPageTest = require('webpagetest');8var wpt = new WebPageTest('www.webpagetest.org');9wpt.checkData('testId', function(err, data) {10 if (err) return console.error(err);11 console.log(data);12});13WebPageTest(url, [options])
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new wpt('API_KEY');3wpt.checkData('test', function(error, data) {4 if (error) {5 console.log(error);6 } else {7 console.log(data);8 }9});10var wpt = require('wpt');11var wpt = new wpt('API_KEY');12wpt.getLocations(function(error, data) {13 if (error) {14 console.log(error);15 } else {16 console.log(data);17 }18});19var wpt = require('wpt');20var wpt = new wpt('API_KEY');21wpt.getTesters(function(error, data) {22 if (error) {23 console.log(error);24 } else {25 console.log(data);26 }27});28var wpt = require('wpt');29var wpt = new wpt('API_KEY');30wpt.getTest('test', function(error, data) {31 if (error) {32 console.log(error);33 } else {34 console.log(data);35 }36});37var wpt = require('wpt');38var wpt = new wpt('API_KEY');39wpt.getTestStatus('test', function(error, data) {40 if (error) {41 console.log(error);42 } else {43 console.log(data);44 }45});46var wpt = require('wpt');47var wpt = new wpt('API_KEY');48wpt.getTestResults('test', function(error, data) {49 if (error) {50 console.log(error);51 } else {52 console.log(data);53 }54});55var wpt = require('wpt');56var wpt = new wpt('API_KEY');57wpt.testStatus('test', function(error, data) {58 if (error) {59 console.log(error);60 } else {61 console.log(data);
Using AI Code Generation
1var wpt = require('./wpt.js');2var wpt = new wpt("API_KEY");3wpt.checkData("TEST_ID", function(data) {4 console.log(data);5});6var wpt = function(apiKey) {7 this.apiKey = apiKey;8};9wpt.prototype.checkData = function(testId, callback) {10 var request = require('request');11 request(url, function (error, response, body) {12 if (!error && response.statusCode == 200) {13 callback(body);14 }15 });16}17module.exports = wpt;
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new wpt('WPT_API_KEY');3wpt.checkData('test', function(err, data) {4 if (err) {5 console.log('Error: ' + err);6 } else {7 console.log(data);8 }9});10var wpt = require('wpt');11var wpt = new wpt('WPT_API_KEY');12wpt.getLocations(function(err, data) {13 if (err) {14 console.log('Error: ' + err);15 } else {16 console.log(data);17 }18});19var wpt = require('wpt');20var wpt = new wpt('WPT_API_KEY');21wpt.getTesters(function(err, data) {22 if (err) {23 console.log('Error: ' + err);24 } else {25 console.log(data);26 }27});28var wpt = require('wpt');29var wpt = new wpt('WPT_API_KEY');30wpt.getTesters(function(err, data) {31 if (err) {32 console.log('Error: ' + err);33 } else {34 console.log(data);35 }36});37var wpt = require('wpt');38var wpt = new wpt('WPT_API_KEY');39wpt.getTesters(function(err, data) {40 if (err) {41 console.log('Error: ' + err);42 } else {43 console.log(data);44 }45});46var wpt = require('wpt');47var wpt = new wpt('WPT_API_KEY');48wpt.getTesters(function(err, data) {49 if (err) {50 console.log('Error: ' + err);51 } else {52 console.log(data);53 }54});55var wpt = require('wpt');56var wpt = new wpt('
Using AI Code Generation
1var wpt = require('wpt');2var WPT = new wpt();3WPT.checkData(function (data) {4 console.log(data);5});6{ statusCode: 200,7 data: 'Data Available' }8var wpt = require('wpt');9var WPT = new wpt();10WPT.checkData(function (data) {11 console.log(data);12});13{ statusCode: 204,14 data: 'No Data' }15var wpt = require('wpt');16var WPT = new wpt();17WPT.checkData(function (data) {18 console.log(data);19});20{ statusCode: 400,21 data: 'Bad Request' }22var wpt = require('wpt');23var WPT = new wpt();24WPT.checkData(function (data) {25 console.log(data);26});27{ statusCode: 401,28 data: 'Unauthorized' }29var wpt = require('wpt');30var WPT = new wpt();31WPT.checkData(function (data) {32 console.log(data);33});34{ statusCode: 403,35 data: 'Forbidden' }36var wpt = require('wpt');37var WPT = new wpt();38WPT.checkData(function (data) {39 console.log(data);40});41{ statusCode: 500,42 data: 'Internal Server Error' }43var wpt = require('wpt');44var WPT = new wpt();45WPT.checkData(function (data) {46 console.log(data);47});48{ statusCode: 503,
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!!