How to use requestDetails method in mountebank

Best JavaScript code snippet using mountebank

web-push-lib.js

Source:web-push-lib.js Github

copy

Full Screen

1'use strict';2const urlBase64 = require('urlsafe-base64');3const url = require('url');4const https = require('https');5const WebPushError = require('./web-push-error.js');6const vapidHelper = require('./vapid-helper.js');7const encryptionHelper = require('./encryption-helper.js');8const webPushConstants = require('./web-push-constants.js');9// Default TTL is four weeks.10const DEFAULT_TTL = 2419200;11let gcmAPIKey = '';12let vapidDetails;13function WebPushLib() {14}15/**16 * When sending messages to a GCM endpoint you need to set the GCM API key17 * by either calling setGMAPIKey() or passing in the API key as an option18 * to sendNotification().19 * @param {string} apiKey The API key to send with the GCM request.20 */21WebPushLib.prototype.setGCMAPIKey = function(apiKey) {22 if (apiKey === null) {23 gcmAPIKey = null;24 return;25 }26 if (typeof apiKey === 'undefined'27 || typeof apiKey !== 'string'28 || apiKey.length === 0) {29 throw new Error('The GCM API Key should be a non-empty string or null.');30 }31 gcmAPIKey = apiKey;32};33/**34 * When making requests where you want to define VAPID details, call this35 * method before sendNotification() or pass in the details and options to36 * sendNotification.37 * @param {string} subject This must be either a URL or a 'mailto:'38 * address. For example: 'https://my-site.com/contact' or39 * 'mailto: contact@my-site.com'40 * @param {string} publicKey The public VAPID key, a URL safe, base64 encoded string41 * @param {string} privateKey The private VAPID key, a URL safe, base64 encoded string.42 */43WebPushLib.prototype.setVapidDetails = function(subject, publicKey, privateKey) {44 if (arguments.length === 1 && arguments[0] === null) {45 vapidDetails = null;46 return;47 }48 vapidHelper.validateSubject(subject);49 vapidHelper.validatePublicKey(publicKey);50 vapidHelper.validatePrivateKey(privateKey);51 vapidDetails = {52 subject: subject,53 publicKey: publicKey,54 privateKey: privateKey55 };56 };57 /**58 * To get the details of a request to trigger a push message, without sending59 * a push notification call this method.60 *61 * This method will throw an error if there is an issue with the input.62 * @param {PushSubscription} subscription The PushSubscription you wish to63 * send the notification to.64 * @param {string|Buffer} [payload] The payload you wish to send to the65 * the user.66 * @param {Object} [options] Options for the GCM API key and67 * vapid keys can be passed in if they are unique for each notification you68 * wish to send.69 * @return {Object} This method returns an Object which70 * contains 'endpoint', 'method', 'headers' and 'payload'.71 */72WebPushLib.prototype.generateRequestDetails = function(subscription, payload, options) {73 if (!subscription || !subscription.endpoint) {74 throw new Error('You must pass in a subscription with at least '75 + 'an endpoint.');76 }77 if (typeof subscription.endpoint !== 'string'78 || subscription.endpoint.length === 0) {79 throw new Error('The subscription endpoint must be a string with '80 + 'a valid URL.');81 }82 if (payload) {83 // Validate the subscription keys84 if (typeof subscription !== 'object' || !subscription.keys85 || !subscription.keys.p256dh86 || !subscription.keys.auth) {87 throw new Error('To send a message with a payload, the '88 + 'subscription must have \'auth\' and \'p256dh\' keys.');89 }90 }91 let currentGCMAPIKey = gcmAPIKey;92 let currentVapidDetails = vapidDetails;93 let timeToLive = DEFAULT_TTL;94 let extraHeaders = {};95 let contentEncoding = webPushConstants.supportedContentEncodings.AES_128_GCM;96 let proxy;97 let agent;98 let timeout;99 if (options) {100 const validOptionKeys = [101 'headers',102 'gcmAPIKey',103 'vapidDetails',104 'TTL',105 'contentEncoding',106 'proxy',107 'agent',108 'timeout'109 ];110 const optionKeys = Object.keys(options);111 for (let i = 0; i < optionKeys.length; i += 1) {112 const optionKey = optionKeys[i];113 if (validOptionKeys.indexOf(optionKey) === -1) {114 throw new Error('\'' + optionKey + '\' is an invalid option. '115 + 'The valid options are [\'' + validOptionKeys.join('\', \'')116 + '\'].');117 }118 }119 if (options.headers) {120 extraHeaders = options.headers;121 let duplicates = Object.keys(extraHeaders)122 .filter(function (header) {123 return typeof options[header] !== 'undefined';124 });125 if (duplicates.length > 0) {126 throw new Error('Duplicated headers defined ['127 + duplicates.join(',') + ']. Please either define the header in the'128 + 'top level options OR in the \'headers\' key.');129 }130 }131 if (options.gcmAPIKey) {132 currentGCMAPIKey = options.gcmAPIKey;133 }134 // Falsy values are allowed here so one can skip Vapid `else if` below and use FCM135 if (options.vapidDetails !== undefined) {136 currentVapidDetails = options.vapidDetails;137 }138 if (options.TTL !== undefined) {139 timeToLive = Number(options.TTL);140 if (timeToLive < 0) {141 throw new Error('TTL should be a number and should be at least 0');142 }143 }144 if (options.contentEncoding) {145 if ((options.contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM146 || options.contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM)) {147 contentEncoding = options.contentEncoding;148 } else {149 throw new Error('Unsupported content encoding specified.');150 }151 }152 if (options.proxy) {153 if (typeof options.proxy === 'string'154 || typeof options.proxy.host === 'string') {155 proxy = options.proxy;156 } else {157 console.warn('Attempt to use proxy option, but invalid type it should be a string or proxy options object.');158 }159 }160 if (options.agent) {161 if (options.agent instanceof https.Agent) {162 if (proxy) {163 console.warn('Agent option will be ignored because proxy option is defined.');164 }165 agent = options.agent;166 } else {167 console.warn('Wrong type for the agent option, it should be an instance of https.Agent.');168 }169 }170 if (typeof options.timeout === 'number') {171 timeout = options.timeout;172 }173 }174 if (typeof timeToLive === 'undefined') {175 timeToLive = DEFAULT_TTL;176 }177 const requestDetails = {178 method: 'POST',179 headers: {180 TTL: timeToLive181 }182 };183 Object.keys(extraHeaders).forEach(function (header) {184 requestDetails.headers[header] = extraHeaders[header];185 });186 let requestPayload = null;187 if (payload) {188 const encrypted = encryptionHelper189 .encrypt(subscription.keys.p256dh, subscription.keys.auth, payload, contentEncoding);190 requestDetails.headers['Content-Length'] = encrypted.cipherText.length;191 requestDetails.headers['Content-Type'] = 'application/octet-stream';192 if (contentEncoding === webPushConstants.supportedContentEncodings.AES_128_GCM) {193 requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_128_GCM;194 } else if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) {195 requestDetails.headers['Content-Encoding'] = webPushConstants.supportedContentEncodings.AES_GCM;196 requestDetails.headers.Encryption = 'salt=' + encrypted.salt;197 requestDetails.headers['Crypto-Key'] = 'dh=' + urlBase64.encode(encrypted.localPublicKey);198 }199 requestPayload = encrypted.cipherText;200 } else {201 requestDetails.headers['Content-Length'] = 0;202 }203 const isGCM = subscription.endpoint.indexOf('https://android.googleapis.com/gcm/send') === 0;204 const isFCM = subscription.endpoint.indexOf('https://fcm.googleapis.com/fcm/send') === 0;205 // VAPID isn't supported by GCM hence the if, else if.206 if (isGCM) {207 if (!currentGCMAPIKey) {208 console.warn('Attempt to send push notification to GCM endpoint, '209 + 'but no GCM key is defined. Please use setGCMApiKey() or add '210 + '\'gcmAPIKey\' as an option.');211 } else {212 requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey;213 }214 } else if (currentVapidDetails) {215 const parsedUrl = url.parse(subscription.endpoint);216 const audience = parsedUrl.protocol + '//'217 + parsedUrl.host;218 const vapidHeaders = vapidHelper.getVapidHeaders(219 audience,220 currentVapidDetails.subject,221 currentVapidDetails.publicKey,222 currentVapidDetails.privateKey,223 contentEncoding224 );225 requestDetails.headers.Authorization = vapidHeaders.Authorization;226 if (contentEncoding === webPushConstants.supportedContentEncodings.AES_GCM) {227 if (requestDetails.headers['Crypto-Key']) {228 requestDetails.headers['Crypto-Key'] += ';'229 + vapidHeaders['Crypto-Key'];230 } else {231 requestDetails.headers['Crypto-Key'] = vapidHeaders['Crypto-Key'];232 }233 }234 } else if (isFCM && currentGCMAPIKey) {235 requestDetails.headers.Authorization = 'key=' + currentGCMAPIKey;236 }237 requestDetails.body = requestPayload;238 requestDetails.endpoint = subscription.endpoint;239 if (proxy) {240 requestDetails.proxy = proxy;241 }242 if (agent) {243 requestDetails.agent = agent;244 }245 if (timeout) {246 requestDetails.timeout = timeout;247 }248 return requestDetails;249 };250/**251 * To send a push notification call this method with a subscription, optional252 * payload and any options.253 * @param {PushSubscription} subscription The PushSubscription you wish to254 * send the notification to.255 * @param {string|Buffer} [payload] The payload you wish to send to the256 * the user.257 * @param {Object} [options] Options for the GCM API key and258 * vapid keys can be passed in if they are unique for each notification you259 * wish to send.260 * @return {Promise} This method returns a Promise which261 * resolves if the sending of the notification was successful, otherwise it262 * rejects.263 */264WebPushLib.prototype.sendNotification = function(subscription, payload, options) {265 let requestDetails;266 try {267 requestDetails = this.generateRequestDetails(subscription, payload, options);268 } catch (err) {269 return Promise.reject(err);270 }271 return new Promise(function(resolve, reject) {272 const httpsOptions = {};273 const urlParts = url.parse(requestDetails.endpoint);274 httpsOptions.hostname = urlParts.hostname;275 httpsOptions.port = urlParts.port;276 httpsOptions.path = urlParts.path;277 httpsOptions.headers = requestDetails.headers;278 httpsOptions.method = requestDetails.method;279 if (requestDetails.timeout) {280 httpsOptions.timeout = requestDetails.timeout;281 }282 if (requestDetails.agent) {283 httpsOptions.agent = requestDetails.agent;284 }285 if (requestDetails.proxy) {286 const HttpsProxyAgent = require('https-proxy-agent'); // eslint-disable-line global-require287 httpsOptions.agent = new HttpsProxyAgent(requestDetails.proxy);288 }289 const pushRequest = https.request(httpsOptions, function(pushResponse) {290 let responseText = '';291 pushResponse.on('data', function(chunk) {292 responseText += chunk;293 });294 pushResponse.on('end', function() {295 if (pushResponse.statusCode < 200 || pushResponse.statusCode > 299) {296 reject(new WebPushError(297 'Received unexpected response code',298 pushResponse.statusCode, pushResponse.headers, responseText, requestDetails.endpoint299 ));300 } else {301 resolve({302 statusCode: pushResponse.statusCode,303 body: responseText,304 headers: pushResponse.headers305 });306 }307 });308 });309 if (requestDetails.timeout) {310 pushRequest.on('timeout', function() {311 pushRequest.destroy(new Error('Socket timeout'));312 });313 }314 pushRequest.on('error', function(e) {315 reject(e);316 });317 if (requestDetails.body) {318 pushRequest.write(requestDetails.body);319 }320 pushRequest.end();321 });322 };...

Full Screen

Full Screen

oneserve-queue.js

Source:oneserve-queue.js Github

copy

Full Screen

1/**2 * dependancies libs:3 * - jquery.js4 */5jQuery.extend({6 7 queueListeners : new Array(),8 9 /**10 * user/pass so that queue entries are persistent across login/logout11 * url - url request12 * type - type of request - 'POST', 'DELETE'13 * objData - object to be send in the request14 * successCallback - a string used invoked on eval function arguments available: 15 * - response16 * - requestData 17 * ie. : new $.UI.callback() or new new $.UI.callback(response, requestData)18 * 19 * errorCallback - a string used invoked on eval function arguments available:20 * - error21 * - status22 * 23 * localData - data which can be read on the callback, ie can contain local(mobile) id so relevant24 * local data can be updated25 */26 RequestDetails: function(url, type, objData, paramName, successCallback, errorCallback, localData) {27 self = this;28 var resource = localStorage.getObject('resource');29 this.user = resource.user;30 this.pass = resource.pass;31 this.url = url;32 this.type = type;33 this.data = JSON.stringify(objData);34 this.paramName = paramName;35 this.successCallback = successCallback;36 this.errorCallback = errorCallback;37 this.location = "";38 this.localData = localData;39 if (localStorage.gps == 'true')40 {41 this.location = getGpsLocation();42 } 43 },44 45 /**46 * Queue object hides underlying storage47 */48 Queue: function() {49 var self = this;50 var QUEUE_NAME = 'updateQueue';51 52 function get(){53 var queue = localStorage.getObject(QUEUE_NAME);54 if (queue == undefined)55 {56 queue = new Array();57 }58 return queue;59 }60 61 function save(queue){62 localStorage.setObject(QUEUE_NAME, queue);63 }64 65 /**66 * adds object at the end of the queue67 */68 this.add = function(object){69 consoleLog("Queue add request to: " + object.url);70 var queue = get(); 71 queue.push(object); 72 save(queue);73 consoleLog("Queue updated: " + object.url);74 consoleLog("Queue size: " + queue.length);75 }76 /**77 * add item on the front of the queue78 */79 this.addFirst = function(object){80 var queue = get();81 queue.unshift(object);82 save(queue);83 }84 this.override = function(queue){85 save(queue);86 }87 this.getAll = function(){88 return get();89 }90 this.hasNext = function(){91 return get().length > 0;92 }93 this.isEmpty = function(){94 return get().length == 0;95 }96 /** 97 * Removes the oldest item from the queue and returns it98 */99 this.pop = function(){100 var queue = get();101 var removed = queue.shift();102 save(queue);103 return removed;104 }105 106 this.clear = function(){107 save(new Array());108 }109 },110 111 /**112 * Send rest request if possible otherwise adds to the queue 113 * usage example:114 * var requestDetails = new $.RequestDetails(deleteActivityUrl + activityId + "/" + activityVersion, 'DELETE', null);115 * var remoteUpdater = new $.RemoteUpdater(); 116 * remoteUpdater.update(requestDetails);117 */118 RemoteUpdater: function(){119 var self = this;120 var updateQueue = new $.Queue();121 122 this.isQueueEmpty = function(){123 return updateQueue.isEmpty();124 }125 126 this.getQueueSize = function(){127 return updateQueue.getAll().length;128 }129 130 this.sendRequest = function(requestDetails, async){ 131 consoleLog("RemoteUpdater: sendRequest:" + requestDetails.url+" async="+async);132 var requestData = requestDetails.data == undefined ? '' : requestDetails.data;133 var paramName = requestDetails.paramName == undefined ? '' : requestDetails.paramName+"=";134 135 // we need a flag to indicate if a request is in progress136 // as they are asynchronous so they don't block UI137 // But requests have to go in order, so date on the server is keep in the correct state138 setUpdateRequestInProgress(self.getQueueSize());139 $.ajax({140 url: requestDetails.url,141 type: requestDetails.type,142 headers: getHeaders(requestDetails.user,requestDetails.pass,'OS-REST-AUTH-TOKEN',requestDetails.location),143 async: async,144 data: paramName+requestData,145 contentType: "application/json",146 success: function(response, status, request)147 {148 //149 //NOTE: 150 // make sure you don't change names of: 'response', 'status', 'request' and151 //'requestDetails' variables as they can be used in the callback methods 152 //153 consoleLog("request successful");154 if(requestDetails.successCallback){155 consoleLog("call callback:"+requestDetails.successCallback);156 eval(requestDetails.successCallback);157 }158 requestDetails.success = true;159 160 setUpdateRequestNotInProgress(self.getQueueSize());161 //this request is complete, its safe to send next one162 self.sendQueue(); 163 },164 // Error handler165 error: function(resp, status, req)166 {167 //set flag so we will retry the request168 requestDetails.success = false;169 170 //genuine response from the server, if 404 or timeout we won't get this value 171 if (resp.status > 401)172 {173 // log for later 174 consoleLog("Error response: "+JSON.stringify(resp));175 }176 if(resp.responseText)177 {178 try { //json conversion may fail here make sure it doesn't179 //ie when tomcat returns 404180 if($.parseJSON(resp.responseText).result){181 //so make sure we won't try again182 requestDetails.success = true;183 }184 }catch(e){185 consoleLog("Got queue error response: "+JSON.stringify(resp));186 }187 }188 189 if(requestDetails.errorCallback){190 eval(requestDetails.errorCallback);191 }192 //why we need this and the callback above?193 //well above is a 'static method' call which doesn't have access to ui as such194 consoleLog("Error processing request: " +status + ", "195 + JSON.stringify(resp) + "," 196 + JSON.stringify(req));197 198 //and on error can be overridden199 //THIS doesn't work with asyc queue - OSD-1075200 //self.onError(status, resp, req, requestDetails);201 202 //if request was unsuccesful due to ie network problem203 //add it back204 if(!requestDetails.success){205 updateQueue.addFirst(requestDetails);206 setUpdateRequestNotInProgress(self.getQueueSize());207 //check offline/online status, this will also trigger send queue208 // added delay so that we don't get a fast loop eg. 403/404/405 etc209 setTimeout(checkOnlineStatus,5000);210 }else{211 setUpdateRequestNotInProgress(self.getQueueSize());212 //finished with the request send next on213 self.sendQueue();214 } 215 }216 });217 }218 219 /**220 * Called just before element is added to the queue221 * if returns true element will be added otherwise won't222 */223 this.onBeforeAddToQueue = function(queue, requestDetails){224 consoleLog('onBeforeAddToQueue:superclass');225 return true;226 }227 228 /**229 * queue given request and triggers send 230 */231 this.update = function(requestDetails){ 232 consoleLog("RemoteUpdater: update:" + updateQueue);233 234 var hasRequestPending = self.isQueueEmpty();235 236 var addToQueue = self.onBeforeAddToQueue(updateQueue, requestDetails);237 238 if(addToQueue){239 consoleLog("Online status: " + !offline());240 consoleLog("RemoteUpdater: queue updated");241 updateQueue.add(requestDetails);242 }else{243 consoleLog("RemoteUpdater: queue not updated");244 }245 updateUiWithQueueCount(self.getQueueSize());246 247 //triggers online - check which in order send queued items248 //Only trigger if queue was empty (before we added item to the queue), 249 //as at the end of each request250 //queue will attempt to send any items left in the queue251 if(hasRequestPending){252 checkOnlineStatus(true);253 }254 }255 256 this.sendQueue = function(){257 //check if we have a update request in progress 258 //(update request are sent through the queue)259 //if we do abort send, as item has been added to the queue260 //it will be send after current request261 if(isUpdateRequestInProgress())262 {263 consoleLog('update in progress: abort sendQueue');264 return;265 }266 267 if(!offline()){268 var currentRequestDetails = null;269 var updateQueue = new $.Queue();270 271 //check if we have anything to send if so send272 if(updateQueue.hasNext() && !isUpdateRequestInProgress()){273 currentRequestDetails = updateQueue.pop();274 this.sendRequest(currentRequestDetails, true);275 }276 consoleLog("Queue processing done, items left:" + updateQueue.getAll().length);277 }else{278 consoleLog('offline: abort sendQueue, checking online');279 checkOnlineStatus(true);280 }281 }282 } 283 ...

Full Screen

Full Screen

requestPoolManager.js

Source:requestPoolManager.js Github

copy

Full Screen

1import external from '../externalModules.js';2import { getMaxSimultaneousRequests } from '../util/getMaxSimultaneousRequests.js';3const requestPool = {4 interaction: [],5 thumbnail: [],6 prefetch: [],7};8const numRequests = {9 interaction: 0,10 thumbnail: 0,11 prefetch: 0,12};13let maxNumRequests = {14 interaction: 6,15 thumbnail: 6,16 prefetch: 5,17};18let awake = false;19const grabDelay = 20;20function addRequest(21 element,22 imageId,23 type,24 preventCache,25 doneCallback,26 failCallback,27 addToBeginning28) {29 if (!requestPool.hasOwnProperty(type)) {30 throw new Error(31 'Request type must be one of interaction, thumbnail, or prefetch'32 );33 }34 if (!element || !imageId) {35 return;36 }37 // Describe the request38 const requestDetails = {39 type,40 imageId,41 preventCache,42 doneCallback,43 failCallback,44 };45 // If this imageId is in the cache, resolve it immediately46 const imageLoadObject = external.cornerstone.imageCache.getImageLoadObject(47 imageId48 );49 if (imageLoadObject) {50 imageLoadObject.promise.then(51 function(image) {52 doneCallback(image);53 },54 function(error) {55 failCallback(error);56 }57 );58 return;59 }60 if (addToBeginning) {61 // Add it to the beginning of the stack62 requestPool[type].unshift(requestDetails);63 } else {64 // Add it to the end of the stack65 requestPool[type].push(requestDetails);66 }67 // Wake up68 awake = true;69}70function clearRequestStack(type) {71 // Console.log('clearRequestStack');72 if (!requestPool.hasOwnProperty(type)) {73 throw new Error(74 'Request type must be one of interaction, thumbnail, or prefetch'75 );76 }77 requestPool[type] = [];78}79function startAgain() {80 if (!awake) {81 return;82 }83 setTimeout(function() {84 startGrabbing();85 }, grabDelay);86}87function sendRequest(requestDetails) {88 const cornerstone = external.cornerstone;89 // Increment the number of current requests of this type90 const type = requestDetails.type;91 numRequests[type]++;92 awake = true;93 const imageId = requestDetails.imageId;94 const doneCallback = requestDetails.doneCallback;95 const failCallback = requestDetails.failCallback;96 // Check if we already have this image promise in the cache97 const imageLoadObject = cornerstone.imageCache.getImageLoadObject(imageId);98 if (imageLoadObject) {99 // If we do, remove from list (when resolved, as we could have100 // Pending prefetch requests) and stop processing this iteration101 imageLoadObject.promise.then(102 function(image) {103 numRequests[type]--;104 // Console.log(numRequests);105 doneCallback(image);106 startAgain();107 },108 function(error) {109 numRequests[type]--;110 // Console.log(numRequests);111 failCallback(error);112 startAgain();113 }114 );115 return;116 }117 function requestTypeToLoadPriority(requestDetails) {118 if (requestDetails.type === 'prefetch') {119 return -5;120 } else if (requestDetails.type === 'interactive') {121 return 0;122 } else if (requestDetails.type === 'thumbnail') {123 return 5;124 }125 }126 const priority = requestTypeToLoadPriority(requestDetails);127 let loader;128 if (requestDetails.preventCache === true) {129 loader = cornerstone.loadImage(imageId, {130 priority,131 type: requestDetails.type,132 });133 } else {134 loader = cornerstone.loadAndCacheImage(imageId, {135 priority,136 type: requestDetails.type,137 });138 }139 // Load and cache the image140 loader.then(141 function(image) {142 numRequests[type]--;143 // Console.log(numRequests);144 doneCallback(image);145 startAgain();146 },147 function(error) {148 numRequests[type]--;149 // Console.log(numRequests);150 failCallback(error);151 startAgain();152 }153 );154}155function startGrabbing() {156 // Begin by grabbing X images157 const maxSimultaneousRequests = getMaxSimultaneousRequests();158 maxNumRequests = {159 interaction: Math.max(maxSimultaneousRequests, 1),160 thumbnail: Math.max(maxSimultaneousRequests - 2, 1),161 prefetch: Math.max(maxSimultaneousRequests - 1, 1),162 };163 const currentRequests =164 numRequests.interaction + numRequests.thumbnail + numRequests.prefetch;165 const requestsToSend = maxSimultaneousRequests - currentRequests;166 for (let i = 0; i < requestsToSend; i++) {167 const requestDetails = getNextRequest();168 if (requestDetails) {169 sendRequest(requestDetails);170 }171 }172}173function getNextRequest() {174 if (175 requestPool.interaction.length &&176 numRequests.interaction < maxNumRequests.interaction177 ) {178 return requestPool.interaction.shift();179 }180 if (181 requestPool.thumbnail.length &&182 numRequests.thumbnail < maxNumRequests.thumbnail183 ) {184 return requestPool.thumbnail.shift();185 }186 if (187 requestPool.prefetch.length &&188 numRequests.prefetch < maxNumRequests.prefetch189 ) {190 return requestPool.prefetch.shift();191 }192 if (193 !requestPool.interaction.length &&194 !requestPool.thumbnail.length &&195 !requestPool.prefetch.length196 ) {197 awake = false;198 }199 return false;200}201function getRequestPool() {202 return requestPool;203}204export default {205 addRequest,206 clearRequestStack,207 startGrabbing,208 getRequestPool,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 headers: {4 },5 json: {6 "stubs": [{7 "responses": [{8 "is": {9 "headers": {10 },11 }12 }]13 }]14 }15};16request(options, function (error, response, body) {17 if (error) {18 console.log(error);19 }20 console.log(response.statusCode);21});22var request = require('request');23var options = {24 headers: {25 }26};27request(options, function (error, response, body) {28 if (error) {29 console.log(error);30 }31 console.log(response.statusCode);32});33var request = require('request');34var options = {35 headers: {36 }37};38request(options, function (error, response, body) {39 if (error) {40 console.log(error);41 }42 console.log(response.statusCode);43});44var request = require('request');45var options = {46 headers: {47 }48};49request(options, function (error, response, body) {50 if (error) {51 console.log(error);52 }53 console.log(response.statusCode);54});55var request = require('request');56var options = {57 headers: {58 },59 json: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 json: {4 {5 {6 "is": {7 "headers": {8 },9 "body": {10 }11 }12 }13 }14 }15};16request(options, function(error, response, body) {17 console.log(body);18});19var request = require('request');20var options = {21 json: {22 {23 {24 "is": {25 "headers": {26 },27 "body": {28 }29 }30 }31 }32 }33};34request(options, function(error, response, body) {35 console.log(body);36});37var request = require('request');38var options = {39 json: {40 {41 {42 "is": {43 "headers": {44 },45 "body": {46 }47 }48 }49 }50 }51};52request(options, function(error, response, body) {53 console.log(body);54});

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3json: {4{5{6"is": {7}8}9}10}11};12request(options, function (error, response, body) {13if (!error && response.statusCode == 201) {14console.log(body);15}16})17var request = require('request');18var options = {19};20request(options, function (error, response, body) {21if (!error && response.statusCode == 200) {22console.log(body);23}24})25var request = require('request');26var options = {27};28request(options, function (error, response, body) {29if (!error && response.statusCode == 200) {30console.log(body);31}32})33var request = require('request');34var options = {35json: {36{37{38"is": {39}40}41}42}43};44request(options, function (error, response, body) {45if (!error && response.statusCode == 201) {46console.log(body);47}48})49{ [Error: connect ECONNREFUSED

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2request({3 json: {4 {5 {6 "is": {7 }8 }9 }10 }11}, function (error, response, body) {12 console.log(body);13});14var request = require('request');15request({16 json: {17 {18 {19 "is": {20 }21 }22 }23 }24}, function (error, response, body) {25 console.log(body);26});27var request = require('request');28request({29 json: {30 {31 {32 "is": {33 }34 }35 }36 }37}, function (error, response, body) {38 console.log(body);39});40var request = require('request');41request({42 json: {43 {44 "is": {45 }46 }47 }48}, function (error, response, body) {49 console.log(body);50});51var request = require('request');52request({

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 json: {4 {5 {6 "is": {7 }8 }9 }10 }11};12request(options, function (error, response, body) {13 if (!error && response.statusCode == 201) {14 console.log(body)15 }16})17var request = require('request');18var options = {19};20request(options, function (error, response, body) {21 if (!error && response.statusCode == 200) {22 console.log(body)23 }24})

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2request.post(url, {3 json: {4 stubs: [{5 predicates: [{6 equals: {7 }8 }],9 responses: [{10 is: {11 headers: {12 },13 }14 }]15 }]16 }17}, function(error, response, body) {18 console.log(body);19});20var request = require('request');21request.post(url, {22 json: {23 stubs: [{24 predicates: [{25 equals: {26 }27 }],28 responses: [{29 is: {30 headers: {31 },32 }33 }]34 }]35 }36}, function(error, response, body) {37 console.log(body);38});39var request = require('request');40request.post(url, {41 json: {42 stubs: [{43 predicates: [{44 equals: {45 }46 }],47 responses: [{48 is: {49 headers: {50 },51 }52 }]53 }]54 }55}, function(error, response, body) {56 console.log(body);57});58var request = require('request');59request.post(url, {60 json: {61 stubs: [{62 predicates: [{63 equals: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var request = require('request');3var fs = require('fs');4var imposter = {5 stubs: [{6 responses: [{7 is: {8 headers: {9 },10 }11 }]12 }]13};14var options = {15 headers: { 'Content-Type': 'application/json' },16};17var callback = function (error, response, body) {18 if (!error && response.statusCode == 201) {19 console.log("Imposter created");20 console.log(body);21 console.log(body);22 mb.stop();23 });24 });25 }26};27mb.start(2525).then(function () {28 request(options, callback);29});

Full Screen

Using AI Code Generation

copy

Full Screen

1const request = require('request');2const options = {3};4function callback(error, response, body) {5 if (!error && response.statusCode == 200) {6 console.log(body);7 }8}9request(options, callback);10const request = require('request');11const options = {12};13function callback(error, response, body) {14 if (!error && response.statusCode == 200) {15 console.log(body);16 }17}18request(options, callback);19[{"port": 8080, "protocol": "http", "numberOfRequests": 0, "requests": []}]

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var mbHelper = require('mountebank-helper');3var assert = require('assert');4var mbPort = 2525;5var mbHost = 'localhost';6var mbProtocol = 'http';7var mbUrl = mbHelper.mbUrl(mbProtocol, mbHost, mbPort);8var imposterPort = 3000;9var imposterProtocol = 'http';10var imposterUrl = mbHelper.imposterUrl(imposterProtocol, imposterPort);11var imposter = {12 {13 {14 is: {15 }16 }17 }18};19mb.create(mbPort, function (error, imposter) {20 assert.ok(!error, error);21 console.log('mb created');22 mbHelper.postImposter(mbUrl, imposter, function (error, imposter) {23 assert.ok(!error, error);24 console.log('imposter created');25 mbHelper.postRequest(mbUrl, imposterPort, imposterProtocol, { path: '/' }, function (error, request) {26 assert.ok(!error, error);27 console.log('request posted');28 mbHelper.postResponse(mbUrl, imposterPort, imposterProtocol, { path: '/' }, { statusCode: 200 }, function (error, response) {29 assert.ok(!error, error);30 console.log('response posted');31 mbHelper.postLog(mbUrl, imposterPort, imposterProtocol, { path: '/' }, function (error, log)

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var fs = require('fs');3request({4}, function (error, response, body) {5 if (error || response.statusCode !== 200) {6 console.log('Error getting request details: ' + error);7 }8 else {9 var requestDetails = body;10 console.log('request details: ' + JSON.stringify(requestDetails));11 var response = generateResponse(requestDetails);12 request({13 }, function (error, response, body) {14 if (error || response.statusCode !== 200) {15 console.log('Error sending response: ' + error);16 }17 else {18 console.log('Response sent');19 }20 });21 }22});23function generateResponse(requestDetails) {24 var response = {25 is: {26 }27 };28 if (requestDetails.query && requestDetails.query.name) {29 response.is.body = 'Hello ' + requestDetails.query.name + '!';30 }31 return response;32}33request details: {"ipAddress":"

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