How to use requestWatcher method in wpt

Best JavaScript code snippet using wpt

node.js

Source:node.js Github

copy

Full Screen

1/**2 * Created by avar and dave on 2/14/17.3 */4import debugFactory from 'debug';5let debug = debugFactory('node::node');6import _ from 'underscore'7import Promise from 'bluebird'8import md5 from 'md5'9import animal from 'animal-id'10import { events } from './enum'11import Server from './server'12import Client from './client'13const _private = new WeakMap();14class WatcherData {15 constructor() {16 this._nodeSet = new Set();17 this._fnSet = new Set();18 }19 getFnSet() {20 // console.log(`getFnSet ${this._event}`);21 return this._fnSet;22 }23 addFn(fn) {24 // console.log(`addFn ${this._event}`);25 if(_.isFunction(fn)) {26 this._fnSet.add(fn);27 }28 }29 removeFn(fn){30 // console.log(`removeFn ${this._event}`);31 if(_.isFunction(fn)) {32 this._fnSet.delete(fn);33 return;34 }35 this._fnSet = new Set();36 }37 addProxyNode(nodeId) {38 // console.log(`addProxyNode ${this._event}`);39 this._nodeSet.add(nodeId);40 }41 hasProxyNode(nodeId) {42 // console.log(`hasProxyNode ${this._event}`);43 return this._nodeSet.has(nodeId);44 }45 getProxyNodeSize() {46 // console.log(`getProxyNodeSize ${this._event}`);47 return this._nodeSet.size;48 }49}50class TickWatcher extends WatcherData {51 constructor(event) {52 super();53 this._event = event;54 }55 addTickListener(fn) {56 this.addFn(fn);57 }58 removeTickListener(fn){59 this.removeFn(fn);60 }61}62class RequestWatcher extends WatcherData{63 constructor(endpoint) {64 super();65 this._endpoint = endpoint;66 }67 addRequestListener(fn) {68 this.addFn(fn);69 }70 removeRequestListener(fn){71 this.removeFn(fn);72 }73}74export default class Node {75 constructor({id, bind, layer}) {76 let _scope = {77 id : id || _generateNodeId(),78 layer : layer || 'default',79 nodeServer : new Server(bind),80 nodeClients : new Map(),81 nodeClientsAddressIndex : new Map(),82 tickWatcherMap: new Map(),83 requestWatcherMap: new Map()84 };85 // ** this data we will use during client connections as to be able to reply client connections with node id86 _scope.nodeServer.setItem("node", _scope.id);87 _scope.nodeServer.setItem("layer", _scope.layer);88 _private.set(this, _scope);89 }90 getId() {91 let _scope = _private.get(this);92 return _scope.id;93 }94 getLayer() {95 let _scope = _private.get(this);96 return _scope.layer;97 }98 getAddress() {99 let _scope = _private.get(this);100 if(_scope.nodeServer) {101 return _scope.nodeServer.getAddress();102 }103 }104 getNodes(layerFilter){105 let _scope = _private.get(this);106 let nodes = [];107 if(_scope.nodeServer) {108 _scope.nodeServer.getOnlineClients().forEach((client) => {109 let {node, layer} = client.getData();110 if(layer == layerFilter) {111 nodes.push(node);112 }113 });114 }115 if(_scope.nodeClients.size) {116 _scope.nodeClients.forEach((client, nodeId) => {117 let actorModel = client.getServerActor();118 if(actorModel.isOnline()) {119 let {node, layer} = actorModel.getData();120 if(layer == layerFilter) {121 nodes.push(node);122 }123 }124 });125 }126 return nodes;127 }128 bind(routerAddress) {129 let _scope = _private.get(this);130 if(!_scope.nodeServer) {131 _scope.nodeServer = new Server();132 }133 return _scope.nodeServer.bind(routerAddress);134 // ** TODO specify what we need under _onNodeConnected ?135 // _scope.nodeServer.on(events.CLIENT_CONNECTED, _onNodeConnected.bind(this));136 }137 unbind() {138 let _scope = _private.get(this);139 if(_scope.nodeServer) {140 return _scope.nodeServer.unbind()141 .then((serverId)=>{142 _scope.nodeServer = null;143 return true;144 });145 }146 return Promise.resolve(() => {147 return false;148 });149 }150 connect(address = 'tcp://127.0.0.1:3000') {151 return new Promise((resolve, reject) => {152 if (typeof address != 'string' || address.length == 0) {153 return reject('Wrong type for argument address');154 }155 let _scope = _private.get(this);156 let addressHash = md5(address);157 let nodeClientPromise = null;158 if (!_scope.nodeClientsAddressIndex.has(addressHash)) {159 let client = new Client();160 let connectMsg = {node: this.getId(), layer : this.getLayer()};161 nodeClientPromise = client.connect(address, { data: connectMsg, response: ['node', 'layer']})162 .then(() => {163 let actorModel = client.getServerActor();164 let {node, layer} = actorModel.getData();165 debug(`Node connected: ${this.getId()} -> ${node}`);166 _scope.nodeClientsAddressIndex.set(addressHash, node);167 _scope.nodeClients.set(node, client);168 _addExistingListenersToClient.bind(this)(client);169 return node;170 });171 } else {172 nodeClientPromise = Promise.resolve(() => {173 let nodeId = _scope.nodeClientsAddressIndex.get(addressHash);174 return nodeId;175 });176 }177 return nodeClientPromise.then((client)=> {178 resolve();179 })180 });181 }182 disconnect(address = 'tcp://127.0.0.1:3000') {183 let addressHash = md5(address);184 return new Promise((resolve, reject) => {185 if (typeof address != 'string' || address.length == 0) {186 return reject('Wrong type for argument address');187 }188 let _scope = _private.get(this);189 if(!_scope.nodeClientsAddressIndex.has(addressHash)) {190 return resolve();191 }192 let nodeId = _scope.nodeClientsAddressIndex.get(addressHash);193 let client = _scope.nodeClients.get(nodeId);194 return client.disconnect().then(() => {195 _removeClientAllListeners.bind(this)(client)196 _scope.nodeClients.delete(nodeId);197 _scope.nodeClientsAddressIndex.delete(addressHash)198 resolve();199 });200 });201 }202 stop() {203 let _scope = _private.get(this);204 let stopPromise = [];205 if(_scope.nodeServer.isOnline()) {206 stopPromise.push(_scope.nodeServer.unbind());207 }208 _scope.nodeClients.forEach((client)=>{209 if(client.isOnline()) {210 stopPromise.push(client.disconnect());211 }212 });213 return Promise.all(stopPromise);214 }215 onRequest(endpoint, fn) {216 let _scope = _private.get(this);217 let requestWatcher = _scope.requestWatcherMap.get(endpoint);218 if(!requestWatcher) {219 requestWatcher = new RequestWatcher(endpoint);220 _scope.requestWatcherMap.set(endpoint, requestWatcher);221 }222 requestWatcher.addRequestListener(fn);223 _scope.nodeServer.onRequest(endpoint, fn);224 _scope.nodeClients.forEach((client)=>{225 client.onRequest(endpoint, fn);226 });227 }228 offRequest(endpoint, fn) {229 let _scope = _private.get(this);230 _scope.nodeServer.offRequest(endpoint);231 _scope.nodeClients.forEach((client)=>{232 client.offRequest(endpoint, fn);233 });234 let requestWatcher = _scope.requestWatcherMap.get(endpoint);235 if(requestWatcher) {236 requestWatcher.removeRequestListener(fn);237 }238 }239 onTick(event, fn) {240 let _scope = _private.get(this);241 let tickWatcher = _scope.tickWatcherMap.get(event);242 if(!tickWatcher) {243 tickWatcher = new TickWatcher(event);244 _scope.tickWatcherMap.set(event, tickWatcher);245 }246 tickWatcher.addTickListener(fn);247 // ** _scope.nodeServer is constructed in Node constructor248 _scope.nodeServer.onTick(event, fn);249 _scope.nodeClients.forEach((client)=>{250 client.onTick(event, fn);251 });252 }253 offTick(event, fn) {254 let _scope = _private.get(this);255 _scope.nodeServer.offTick(event);256 _scope.nodeClients.forEach((client)=>{257 client.offTick(event, fn);258 });259 let tickWatcher = _scope.tickWatcherMap.get(event);260 if(tickWatcher) {261 tickWatcher.removeTickListener(fn);262 }263 }264 request(nodeId, endpoint, data, timeout = 5000) {265 let _scope = _private.get(this);266 let clientActor = _getClientByNode.bind(this)(nodeId);267 if(clientActor) {268 return _scope.nodeServer.request(clientActor.getId(), endpoint, data, timeout);269 }270 if(_scope.nodeClients.has(nodeId)) {271 // ** nodeId is the serverId of node so we request272 return _scope.nodeClients.get(nodeId).request(endpoint, data, timeout )273 }274 }275 tick(nodeId, event, data) {276 let _scope = _private.get(this);277 let clientActor = _getClientByNode.bind(this)(nodeId);278 if(clientActor) {279 return _scope.nodeServer.tick(clientActor.getId(), event, data);280 }281 if(_scope.nodeClients.has(nodeId)) {282 // ** nodeId is the serverId of node so we request283 return _scope.nodeClients.get(nodeId).tick(event, data);284 }285 return Promise.reject(`Node with ${nodeId} is not found.`);286 }287 requestLayerAny(layer, endpoint, data, timeout = 5000) {288 let layerNodes = this.getNodes(layer);289 let nodeId = _getWinnerNode.bind(this)(layerNodes, endpoint);290 return this.request(nodeId, endpoint, data, timeout);291 }292 tickLayerAny(layer, event, data) {293 let layerNodes = this.getNodes(layer);294 let nodeId = _getWinnerNode.bind(this)(layerNodes, event);295 return this.tick(nodeId, event, data);296 }297 tickLayer(layer, event, data) {298 let layerNodes = this.getNodes(layer);299 let tickPromises = [];300 layerNodes.forEach((nodeId)=> {301 tickPromises.push(this.tick(nodeId, event, data));302 });303 return Promise.all(tickPromises);304 }305 // ** TODO what if we add a fn to process data306 // ** we can proxy event to multiple endpoints307 proxyTick(eventsToProxy, nodeId, fn) {308 if(_.isString(eventsToProxy)) {309 eventsToProxy = [eventsToProxy];310 }311 let _scope = _private.get(this);312 eventsToProxy.forEach( (event) => {313 _proxyTickToNode.bind(this)(event, nodeId);314 }, this);315 }316 // ** TODO what if we add a fn to process data317 // ** we can proxy endpoint to just one endpoint318 proxyRequest(fromEndpoint, toNodeId, toEndpoint, timeout = 5000) {319 let _scope = _private.get(this);320 console.log( "proxyRequest", _scope.requestWatcherMap);321 let _self = this;322 toEndpoint = toEndpoint ? toEndpoint : fromEndpoint;323 let requestWatcher = _scope.requestWatcherMap.get(fromEndpoint);324 if(!requestWatcher) {325 requestWatcher = new RequestWatcher(fromEndpoint);326 _scope.requestWatcherMap.set(fromEndpoint, requestWatcher);327 }328 if(requestWatcher.getProxyNodesSize() > 0) {329 return Promise.reject(`Already has a proxy for ${fromEndpoint}`);330 }331 requestWatcher.addProxyNode(toNodeId);332 _self.onRequest(fromEndpoint, function(request){333 let data = request.body;334 _self.request(toNodeId, toEndpoint, data, timeout)335 .then((responseData) => {336 request.reply(responseData);337 });338 });339 return Promise.resolve(fromEndpoint);340 }341}342// ** PRIVATE FUNCTIONS343function _getClientByNode(nodeId) {344 let _scope = _private.get(this);345 let actors = _scope.nodeServer.getOnlineClients().filter((actor) => {346 let { node } = actor.getData();347 return node == nodeId;348 });349 if(!actors.length) {350 return null;351 }352 if(actors.length > 1) {353 return debug(`We should have just 1 client from 1 node`);354 }355 return actors[0];356}357function _generateNodeId() {358 return animal.getId();359}360function _getWinnerNode(nodeIds, tag) {361 let len = nodeIds.length;362 let idx = Math.floor(Math.random() * len);363 return nodeIds[idx];364}365function _proxyTickToNode(event, nodeId) {366 let _scope = _private.get(this);367 let tickWatcher = _scope.tickWatcherMap.get(event);368 if(!tickWatcher) {369 tickWatcher = new TickWatcher(event);370 _scope.tickWatcherMap.set(event, tickWatcher);371 }372 // ** to be sure that we are adding onTick for each node just once373 if(!tickWatcher.hasProxyNode(nodeId)) {374 tickWatcher.addProxyNode(nodeId);375 this.onTick(event, (data) => {376 this.tick(nodeId, event, data);377 });378 }379}380function _addExistingListenersToClient(client) {381 let _scope = _private.get(this);382 // ** adding previously added onTick-s for this client to383 _scope.tickWatcherMap.forEach((tickWatcher, event) => {384 // ** TODO what about order of functions ?385 tickWatcher.getFnSet().forEach((fn) => {386 client.onTick(event, fn.bind(this));387 }, this);388 }, this);389 // ** adding previously added onRequests-s for this client to390 _scope.requestWatcherMap.forEach((requestWatcher, endpoint) => {391 // ** TODO what about order of functions ?392 requestWatcher.getFnSet().forEach((fn) => {393 client.onRequest(endpoint, fn.bind(this));394 }, this);395 }, this);396}397function _removeClientAllListeners(client) {398 let _scope = _private.get(this);399 // ** adding previously added onTick-s for this client to400 _scope.tickWatcherMap.forEach((tickWatcher, event) => {401 client.offTick(event, fn.bind(this));402 }, this);403 // ** adding previously added onRequests-s for this client to404 _scope.requestWatcherMap.forEach((requestWatcher, endpoint) => {405 client.offRequest(endpoint);406 }, this);...

Full Screen

Full Screen

index.ts

Source:index.ts Github

copy

Full Screen

1import { SpiderGlobal } from './utils/SpiderGlobal';2import { Track } from './track';3import { IShowAreaTimeParams, IGlobalOptions } from './interface';4import { RequestWatcher } from './utils/RequestWatcher';5import { PageWatcher } from './utils/PageWatcher';6export * from './interface';7export * from './interface/Track';8export {9 RequestWatcher10};11export default class Spider {12 private track: Track;13 requestWatcher: RequestWatcher;14 constructor(options?: IGlobalOptions) {15 const global = new SpiderGlobal();16 global.init(options);17 const pageWatcher = new PageWatcher(global);18 this.requestWatcher = new RequestWatcher(global);19 this.track = new Track(global, pageWatcher, this.requestWatcher)20 this.track.init();21 }22 reportPageStay() {23 this.track.reportPageStay();24 }25 reportShowElements(params: IShowAreaTimeParams[]) {26 this.track.reportShowElements(params);27 }28 pauseReportShowElements(showNames?: string[]) {29 this.track.pauseReportShowElements(showNames);30 }31 resumeReportShowElements() {32 this.track.resumeReportShowElements();33 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if(err) {4 console.log('Error: ' + err);5 } else {6 console.log(data);7 }8});9### WebPageTest(host, key, port, https, timeout, apiVersion)10### test(url, options, callback)11### runTest(url, options, callback)12### getTestStatus(testId, callback)

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('wpt');2const wptHook = new wpt(process.env.WPT_API_KEY, process.env.WPT_HOST);3const test = async () => {4 const result = await wptHook.requestWatcher(testId);5 console.log(result);6};7test();8const wpt = require('wpt');9const wptHook = new wpt(process.env.WPT_API_KEY, process.env.WPT_HOST);10const test = async () => {11 const result = await wptHook.getTestResults(testId);12 console.log(result);13};14test();15const wpt = require('wpt');16const wptHook = new wpt(process.env.WPT_API_KEY, process.env.WPT_HOST);17const test = async () => {18 const result = await wptHook.getTestStatus(testId);19 console.log(result);20};21test();22const wpt = require('wpt');23const wptHook = new wpt(process.env.WPT_API_KEY, process.env.WPT_HOST);24const test = async () => {25 const result = await wptHook.getTestInfo(testId);26 console.log(result);27};28test();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.1ab7d9b2e2b7c0a6f4e6c0f6d3b7c0a6');3var testID = process.argv[2];4var wpt = require('webpagetest');5var wpt = new WebPageTest('www.webpagetest.org', 'A.1ab7d9b2e2b7c0a6f4e6c0f6d3b7c0a6');6var testID = process.argv[2];7var wpt = require('webpagetest');8var wpt = new WebPageTest('www.webpagetest.org', 'A.1ab7d9b2e2b7c0a6f4e6c0f6d3b7c0a6');9var testID = process.argv[2];10var wpt = require('webpagetest');11var wpt = new WebPageTest('www.webpagetest.org', 'A.1ab7d9b2e2b7c0a6f4e6c0f6d3b7c0a6');12var testID = process.argv[2];13var wpt = require('webpagetest');14var wpt = new WebPageTest('www.webpagetest.org', 'A.1ab7d9b2e2b7c0a6f4e6c0f6d3b7c0a6');15var testID = process.argv[2];16var wpt = require('webpagetest');17var wpt = new WebPageTest('www.webpagetest.org', 'A.1ab7d9b2e2b7c0a6f4e6c0f6d3b7c0a6');18var testID = process.argv[2];19var wpt = require('webpagetest');20var wpt = new WebPageTest('www.webpagetest.org', 'A.1ab7d9b2e2b7c0a6f4e6c0f6d3b7c0a6

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt-api');2var options = {3};4wpt.requestWatcher(options, function (error, data) {5 if (error) {6 console.log(error);7 } else {8 console.log(data);9 }10});

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 wpt 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