How to use this.requestLib method in Cypress

Best JavaScript code snippet using cypress

HttpClient.js

Source:HttpClient.js Github

copy

Full Screen

1var https = require("https");2var http = require("http");3var request = require("request");4var querystring = require("query-string");5var URL = require("url").URL;6const isValidUrl = (s) => {7 if (!s || s === null) return false;8 try {9 if (s === "api.nexmo.com") return s;10 let o = new URL(s);11 return o.host;12 } catch (err) {13 return false;14 }15};16class HttpClient {17 constructor(options, credentials) {18 let hostOverride = isValidUrl(options.host);19 this.credentials = credentials;20 this.host = hostOverride ? hostOverride : `rest.nexmo.com`;21 this.port = options.port || 443;22 this.https = options.https || https;23 this.http = options.http || http;24 this.headers = {25 "Content-Type": "application/x-www-form-urlencoded",26 Accept: "application/json",27 };28 this.logger = options.logger;29 this.timeout = options.timeout;30 this.requestLib = request;31 if (options.userAgent) {32 this.headers["User-Agent"] = options.userAgent;33 }34 }35 request(36 endpoint,37 method,38 callback,39 skipJsonParsing = false,40 customResponseParser41 ) {42 if (typeof method === "function") {43 callback = method;44 endpoint.method = endpoint.method || "GET";45 } else if (typeof method !== "undefined") {46 endpoint.method = method;47 }48 var options = {49 host: endpoint.host ? endpoint.host : this.host,50 port: this.port,51 path: endpoint.path,52 method: endpoint.method,53 headers: Object.assign({}, this.headers, endpoint.headers),54 };55 if (this.timeout !== undefined) {56 options.timeout = this.timeout;57 }58 // Allow existing headers to be overridden59 // Allow new headers to be added60 if (endpoint.headers) {61 Object.keys(endpoint.headers).forEach(function (key) {62 options.headers[key] = endpoint.headers[key];63 });64 }65 // the output here can returnn one of two options:66 // - Using `sig` & `timestamp` in the JSON body67 // - Using `sig` & `timestamp` in the query string68 if (this.credentials.signatureSecret && this.credentials.signatureMethod) {69 // you must first add a timestamp70 let params;71 let splitPath;72 let path;73 // determine if the response should be querystring or JSON body74 if (!endpoint.body) {75 // this branch is for query string76 splitPath = options.path.split(/\?(.+)/);77 path = splitPath[0];78 params = querystring.parse(splitPath[1]);79 } else {80 // this section is for JSON body81 params = JSON.parse(endpoint.body);82 }83 // add timestamp if not already present84 if (!params.timestamp) {85 params.timestamp = ((new Date().getTime() / 1000) | 0).toString();86 }87 // strip API Secret88 delete params.api_secret;89 let hash = this.credentials.generateSignature(params);90 params.sig = hash;91 if (!endpoint.body) {92 //this section is for querystring93 let query = "";94 // rebuild query95 Object.keys(params)96 .sort()97 .forEach((key) => {98 query += "&" + key + "=" + encodeURI(params[key]);99 });100 // replace the first & with ?101 query = query.replace(/&/i, "?");102 options.path = `${path}${query}`;103 } else {104 endpoint.body = JSON.stringify(params);105 }106 }107 this.logger.info("Request:", options, "\nBody:", endpoint.body);108 var request;109 if (options.port === 443) {110 request = this.https.request(options);111 } else {112 request = this.http.request(options);113 }114 request.end(endpoint.body);115 // Keep an array of String or Buffers,116 // depending on content type (binary or JSON) of response117 var responseData = [];118 request.on("response", (response) => {119 var isBinary =120 response.headers["content-type"] === "application/octet-stream";121 if (!isBinary) {122 response.setEncoding("utf8");123 }124 response.on("data", (chunk) => {125 responseData.push(chunk);126 });127 response.on("end", () => {128 this.logger.info("response ended:", response.statusCode);129 if (callback) {130 if (isBinary) {131 responseData = Buffer.concat(responseData);132 }133 this.__parseResponse(134 response,135 responseData,136 endpoint.method,137 callback,138 skipJsonParsing,139 customResponseParser140 );141 }142 });143 response.on("close", (e) => {144 if (e) {145 this.logger.error(146 "problem with API request detailed stacktrace below "147 );148 this.logger.error(e);149 callback(e);150 }151 });152 });153 request.on("error", (e) => {154 this.logger.error("problem with API request detailed stacktrace below ");155 this.logger.error(e);156 callback(e);157 });158 }159 __parseResponse(160 httpResponse,161 data,162 method,163 callback,164 skipJsonParsing,165 customResponseParser166 ) {167 const isArrayOrBuffer = data instanceof Array || data instanceof Buffer;168 if (!isArrayOrBuffer) {169 throw new Error("data should be of type Array or Buffer");170 }171 const status = httpResponse.statusCode;172 const headers = httpResponse.headers;173 let response = null;174 var error = null;175 try {176 if (status >= 500) {177 error = {178 message: "Server Error",179 statusCode: status,180 };181 } else if (182 httpResponse.headers["content-type"] === "application/octet-stream"183 ) {184 response = data;185 } else if (status === 429) {186 // 429 does not return a parsable body187 if (!headers["retry-after"]) {188 // retry based on allowed per second189 const retryAfterMillis = method === "POST" ? 1000 / 2 : 1000 / 5;190 headers["retry-after"] = retryAfterMillis;191 }192 error = {193 body: data.join(""),194 };195 } else if (status === 204) {196 response = null;197 } else if (status >= 400 || status < 200) {198 error = {199 body: JSON.parse(data.join("")),200 headers,201 };202 } else if (method !== "DELETE") {203 if (!!skipJsonParsing) {204 response = data.join("");205 } else {206 response = JSON.parse(data.join(""));207 }208 } else {209 response = data;210 }211 } catch (parseError) {212 this.logger.error(parseError);213 this.logger.error(214 "could not convert API response to JSON, above error is ignored and raw API response is returned to client"215 );216 this.logger.error("Raw Error message from API ");217 this.logger.error(`"${data}"`);218 error = {219 status: status,220 message: "The API response could not be parsed.",221 body: data.join(""),222 parseError: parseError,223 };224 }225 if (error) {226 error.statusCode = status;227 error.headers = headers;228 }229 if (typeof callback === "function") {230 if (typeof customResponseParser === "function") {231 // don't try to parse the response on errors232 if (response) {233 response = customResponseParser(response);234 }235 }236 callback(error, response);237 }238 }239 _addLimitedAccessMessageToErrors(callback, limitedAccessStatus) {240 return function (err, data) {241 if (err && err.status == limitedAccessStatus) {242 err._INFO_ =243 "This endpoint may need activating on your account. Please email support@nexmo.com for more information";244 }245 return callback(err, data);246 };247 }248 get(path, params, callback, useJwt = false, useBasicAuth = false) {249 if (!callback) {250 if (typeof params == "function") {251 callback = params;252 params = {};253 }254 }255 params = params || {};256 if (!useJwt && !useBasicAuth) {257 params["api_key"] = this.credentials.apiKey;258 params["api_secret"] = this.credentials.apiSecret;259 }260 path = path + "?" + querystring.stringify(params);261 const headers = {262 "Content-Type": "application/json",263 };264 if (useJwt) {265 headers["Authorization"] = `Bearer ${this.credentials.generateJwt()}`;266 }267 if (useBasicAuth) {268 headers["Authorization"] = `Basic ${Buffer.from(269 this.credentials.apiKey + ":" + this.credentials.apiSecret270 ).toString("base64")}`;271 }272 this.request(273 {274 path: path,275 headers,276 },277 "GET",278 callback279 );280 }281 delete(path, callback, useJwt, useBasicAuth) {282 let params = {};283 if (!useJwt && !useBasicAuth) {284 params["api_key"] = this.credentials.apiKey;285 params["api_secret"] = this.credentials.apiSecret;286 }287 let headers = {};288 if (useBasicAuth) {289 headers["Authorization"] = `Basic ${Buffer.from(290 this.credentials.apiKey + ":" + this.credentials.apiSecret291 ).toString("base64")}`;292 }293 path = path + "?" + querystring.stringify(params);294 this.request(295 {296 path: path,297 headers,298 },299 "DELETE",300 callback301 );302 }303 postFile(path, options, callback, useJwt) {304 let qs = {};305 if (!useJwt) {306 qs["api_key"] = this.credentials.apiKey;307 qs["api_secret"] = this.credentials.apiSecret;308 }309 if (Object.keys(qs).length) {310 let joinChar = "?";311 if (path.indexOf(joinChar) !== -1) {312 joinChar = "&";313 }314 path = path + joinChar + querystring.stringify(qs);315 }316 const file = options.file;317 delete options.file; // We don't send this as metadata318 const formData = {};319 if (file) {320 formData["filedata"] = {321 value: file,322 options: {323 filename: options.filename || null,324 },325 };326 }327 if (options.info) {328 formData.info = JSON.stringify(options.info);329 }330 if (options.url) {331 formData.url = options.url;332 }333 let protocol = this.port === 443 ? "https://" : "http://";334 this.requestLib.post(335 {336 url: protocol + this.host + path,337 formData: formData,338 headers: {339 Authorization: `Bearer ${this.credentials.generateJwt()}`,340 },341 },342 callback343 );344 }345 post(path, params, callback, useJwt) {346 let qs = {};347 if (!useJwt) {348 qs["api_key"] = this.credentials.apiKey;349 qs["api_secret"] = this.credentials.apiSecret;350 }351 let joinChar = "?";352 if (path.indexOf(joinChar) !== -1) {353 joinChar = "&";354 }355 path = path + joinChar + querystring.stringify(qs);356 this.request(357 {358 path: path,359 body: querystring.stringify(params),360 },361 "POST",362 callback363 );364 }365 postJson(path, params, callback, useJwt, useBasicAuth) {366 let qs = {};367 if (!useJwt && !useBasicAuth) {368 qs["api_key"] = this.credentials.apiKey;369 qs["api_secret"] = this.credentials.apiSecret;370 }371 let joinChar = "?";372 if (path.indexOf(joinChar) !== -1) {373 joinChar = "&";374 }375 path = path + joinChar + querystring.stringify(qs);376 let headers = {377 "Content-Type": "application/json",378 };379 if (useBasicAuth) {380 headers["Authorization"] = `Basic ${Buffer.from(381 this.credentials.apiKey + ":" + this.credentials.apiSecret382 ).toString("base64")}`;383 }384 this.request(385 {386 path: path,387 body: JSON.stringify(params),388 headers,389 },390 "POST",391 callback392 );393 }394 postUseQueryString(path, params, callback, useJwt) {395 params = params || {};396 if (!useJwt) {397 params["api_key"] = this.credentials.apiKey;398 params["api_secret"] = this.credentials.apiSecret;399 }400 path = path + "?" + querystring.stringify(params);401 this.request(402 {403 path: path,404 },405 "POST",406 callback407 );408 }409}...

Full Screen

Full Screen

api.js

Source:api.js Github

copy

Full Screen

1const Asset = require("./common/asset");2const AssetProperties = require('./common/assetproperties');3const Report = require("./common/report");4const Tools = require("./common/tools");5const Util = require("./common/util");6const Workflow = require("./common/workflow");7const apiErrors = {8 InstanceNameInvalid: 19}10/********************************************11 * Javascript API for utilizing the crownpeak API12 * All function are asyncronous and are operated upon by13 * promises14 *15 ********************************************/16class api {17 constructor() {18 this.host;19 this.instance;20 this.apiKey;21 this._isAuthenticated = false;22 this._error;23 this.cookie;24 this.https = require("https");25 this.requestLib = require('request-promise');26 this.webAPIRoot = "/cpt_webservice/accessapi/";27 this.Asset = new Asset(this);28 this.AssetProperties = new AssetProperties(this);29 this.Report = new Report(this);30 this.Tools = new Tools(this);31 this.Workflow = new Workflow(this);32 }33 get isAuthenticated() {34 return this._isAuthenticated;35 }36 get error() {37 return this._error;38 }39 /**40 * Authenticate the user such that all other function can run41 * @param {string} username - The username of the user42 * @param {string} password - The password of the user43 * @param {string} host - The host of the user44 * @param {string} instance45 * @param {string} apiKey46 */47 async login(username, password, host, instance, apiKey) {48 this.host = host;49 this.instance = instance;50 this.apiKey = apiKey;51 var apiParent = this;52 var parentResponse; //Store the response for return of the await53 var parentError; //Store the error54 var authJson = {55 "instance": instance,56 "username": username,57 "password": password,58 "remember_me": "false",59 "timeZoneOffsetMinutes": "-480"60 };61 await this.postRequest("/Auth/Authenticate", authJson,62 function(response) {63 parentResponse = response;64 },65 function(error) {66 parentError = error;67 });68 if (parentResponse !== undefined && Util.IsValidJSONString(parentResponse.body)) {69 var jsonBody = JSON.parse(parentResponse.body);70 if (jsonBody.resultCode === Util.ResponseMessages.Success) {71 //User was successfully authenticated72 this._isAuthenticated = true;73 this.cookie = parentResponse.headers["set-cookie"];74 } else {75 this._error = parentResponse;76 }77 } else {78 if (parentError !== undefined && Util.IsValidJSONString(parentError.error)) {79 this._error = parentError;80 throw parentError;81 }82 throw Error("Unable to contact CMS, please check your settings");83 }84 return parentResponse;85 }86 static currentDate() {87 var today = new Date();88 var dd = String(today.getDate()).padStart(2, '0');89 var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!90 var yyyy = today.getFullYear();91 return mm + '/' + dd + '/' + yyyy;92 }93 /**94 *95 * @param {string} urlPath - The path to call from the url96 * @param {JSON|string} data - The data to send in the request97 * @param {function(object)} callback - function to run on succes98 * @param {function(object)} onError - function to run on error99 */100 async postRequest(urlPath, data, callback, onError) {101 var currentAPI = this;102 var attempt = 0;103 if (urlPath.startsWith("/")) {104 urlPath = urlPath.substring(1, urlPath.length);105 }106 const options = {107 url: "https://" + this.host + "/" + this.instance + this.webAPIRoot + urlPath, //URL of the instance108 headers: {109 'x-api-key': this.apiKey, //The API Key110 'accept': 'application/json', //Data is returned in JSON format111 'Content-Type': 'text/json', //Data is sent in JSON format112 'cp-datetime': api.currentDate() //The current datetime113 },114 body: JSON.stringify(data),115 //proxy: "http://127.0.0.1:8888",116 resolveWithFullResponse: true,117 method: "POST"118 }119 if (this._isAuthenticated) {120 options.headers.cookie = this.cookie;121 }122 try {123 var response = await this.requestLib.post(options);124 callback(response);125 } catch (error) {126 var timeoutWait = Util.InitialTimeoutWait;127 if (error !== undefined && error["statusCode"] == Util.StatusCode.Timeout && attempt < 3) {128 attempt++;129 /*If error is a timeout, then retry either after the given retry amount in Retry-After isn't set,130 otherwise use the time given */131 if (error.response !== undefined && error.response.headers !== undefined && error.response.headers["retry-after"] !== undefined) {132 var retryAfter = parseInt(error.response.headers["retry-after"], 10);133 if (retryAfter != "NaN") {134 timeoutWait = retryAfter * 1000;135 }136 }137 await Util.timeout(timeoutWait);138 await currentAPI.postRequest(urlPath, data, callback, onError);139 } else {140 if (onError !== undefined) {141 onError(error);142 }143 }144 }145 }146 /**147 *148 * @param {string} urlPath - The path to call from the url149 * @param {function(object)} callback - function to run on success150 * @param {function(object)=} onError - function to run on error151 */152 async getCmsRequest(urlPath, callback, onError) {153 var currentAPI = this;154 var attempt = 0;155 if (urlPath.startsWith("/")) {156 urlPath = urlPath.substring(1, urlPath.length);157 }158 const options = {159 url: "https://" + this.host + "/" + urlPath, //URL of the instance160 headers: {},161 resolveWithFullResponse: true,162 method: "GET",163 encoding: null164 }165 if (this._isAuthenticated) {166 options.headers.cookie = this.cookie;167 }168 try {169 var response = await this.requestLib.get(options);170 callback(response);171 } catch (error) {172 var timeoutWait = Util.InitialTimeoutWait;173 if (error !== undefined && error["statusCode"] == Util.StatusCode.Timeout && attempt < 3) {174 attempt++;175 /*If error is a timeout, then retry either after the given retry amount in Retry-After isn't set,176 otherwise use the time given */177 if (error.response !== undefined && error.response.headers !== undefined && error.response.headers["retry-after"] !== undefined) {178 var retryAfter = parseInt(error.response.headers["retry-after"], 10);179 if (retryAfter != "NaN") {180 timeoutWait = retryAfter * 1000;181 }182 }183 await Util.timeout(timeoutWait);184 await currentAPI.getCmsRequest(urlPath, callback, onError);185 } else {186 if (onError !== undefined) {187 onError(error);188 }189 }190 }191 }192 /**193 *194 * @param {string} urlPath - The path to call from the url195 * @param {JSON|string} data - The data to send in the request196 * @param {function(object)} callback - function to run on succes197 * @param {function(object)} onError - function to run on error198 */199 postRequestV1(urlPath, data, callback, onError) {200 var currentAPI = this;201 var attempt = 0;202 if (urlPath.startsWith("/")) {203 urlPath = urlPath.substring(1, urlPath.length);204 }205 const options = {206 url: "https://" + this.host + "/" + this.instance + this.webAPIRoot + urlPath, //URL of the instance207 headers: {208 'x-api-key': this.apiKey, //The API Key209 'accept': 'application/json', //Data is returned in JSON format210 'Content-Type': 'text/json', //Data is sent in JSON format211 'cp-datetime': api.currentDate() //The current datetime212 },213 body: JSON.stringify(data),214 //proxy: "http://127.0.0.1:8888",215 resolveWithFullResponse: true,216 method: "POST"217 }218 if (this._isAuthenticated) {219 options.headers.cookie = this.cookie;220 }221 return this.requestLib.post(options).then(callback).catch(222 function(error) {223 var timeoutWait = Util.InitialTimeoutWait;224 if (error !== undefined && error["statusCode"] == Util.StatusCode.Timeout && attempt < 3) {225 attempt++;226 /*If error is a timeout, then retry either after the given retry amount in Retry-After isn't set,227 otherwise use the time given */228 if (error.response !== undefined && error.response.headers !== undefined && error.response.headers["retry-after"] !== undefined) {229 var retryAfter = parseInt(error.response.headers["retry-after"], 10);230 if (retryAfter != "NaN") {231 timeoutWait = retryAfter * 1000;232 }233 }234 setTimeout(currentAPI.postRequest(urlPath, data, callback, onError), timeoutWait);235 } else {236 if (onError !== undefined) {237 onError(error);238 }239 }240 }241 );242 }243 Asset = Asset;244 AssetProperties = AssetProperties;245 Report = Report;246 Tools = Tools;247 Util = Util;248 Workflow = Workflow;249}...

Full Screen

Full Screen

deferred-source-map-cache.js

Source:deferred-source-map-cache.js Github

copy

Full Screen

...100 headers,101 timeout: 5000,102 };103 try {104 const { body } = yield this.requestLib(req, true);105 return body;106 }107 catch (error) {108 // eslint-disable-next-line no-console109 debug('got an error loading user-provided sourcemap, serving proxy-generated sourcemap only %o', { url: request.url, headers, error });110 }111 });112 }113 resolve(uniqueId, headers) {114 return __awaiter(this, void 0, void 0, function* () {115 const request = this._getRequestById(uniqueId);116 if (!request) {117 throw new Error(`Missing request with ID '${uniqueId}'`);118 }...

Full Screen

Full Screen

up-wp-cart.js

Source:up-wp-cart.js Github

copy

Full Screen

1function WPCart() {2 this.requestLib = 'jquery';3 this.baseAjaxUrl = this.urlJoin([4 WPCartData.homeUrl, 5 'wp-json',6 WPCartData.UPWPCART_API_BASE,7 WPCartData.UPWPCART_API_ROUTE, 8 ]);9 this.errorPrefix = 'UPWPCart';10}11WPCart.prototype.urlJoin = function (pathStrings) {12 this.throwTypeError(pathStrings, 'Array');13 var trimmedPaths = pathStrings.map(function (pathString) {14 var newPathString = String(pathString);15 if (newPathString.slice(0, 1) == '/') {16 newPathString = newPathString.slice(1);17 }18 if (newPathString.slice(-1) == '/') {19 newPathString = newPathString.slice(0, -1);20 }21 return newPathString;22 });23 return trimmedPaths.join('/');24};25WPCart.prototype.throwRequestLibError = function (requestLib) {26 var message;27 if (requestLib) {28 message = "Request lib: '" + requestLib + "' is not defined!";29 } else {30 message = 'No request library available!';31 }32 throw new Error(this.errorPrefix + ': ' + message);33};34WPCart.prototype.throwUndefObj = function (obj, objName) {35 if (typeof obj === 'undefined') {36 throw new Error(this.errorPrefix + ': ' + 'Object is not defined: ' + objName);37 }38};39WPCart.prototype.throwTypeError = function(obj, typeObj){40 41 var assertion;42 switch(typeObj){43 case 'Array':44 assertion = !(obj instanceof Array);45 break;46 case 'Integer':47 assertion = !Number.isInteger(obj);48 break;49 default:50 assertion = typeof obj !== typeObj; 51 }52 if (assertion) {53 throw new Error(this.errorPrefix + ': ' + "Invalid type: Parameter '" + obj + "' is not '" + typeObj + "'.");54 } 55 56}57WPCart.prototype.jqueryAjaxHandle = function (options) {58 var jquery;59 if (typeof jQuery !== 'undefined') {60 jquery = jQuery;61 } else if (typeof $ !== 'undefined') {62 jquery = $;63 } else {64 this.throwRequestLibError(this.requestLib);65 }66 if (typeof jquery !== 'undefined') {67 jquery.ajax(options);68 }69};70WPCart.prototype.ajax = function (params) {71 this.throwUndefObj(params, 'ajaxParams');72 this.throwTypeError(params, 'object');73 this.throwUndefObj(params.url, 'ajax.params.url');74 this.throwTypeError(params.url, 'string');75 var defaults = {76 method: 'GET',77 };78 var options = Object.assign({}, defaults, params);79 switch (this.requestLib) {80 case 'jquery':81 this.jqueryAjaxHandle(options);82 break;83 default:84 this.throwRequestLibError();85 }86};87WPCart.prototype.ajaxGet = function (params) {88 this.throwUndefObj(params, 'ajaxGetParams');89 this.throwTypeError(params, 'object');90 this.throwUndefObj(params.url, 'ajaxGet.params.url');91 this.throwTypeError(params.url, 'string');92 93 params.method = 'GET';94 this.ajax(params);95};96WPCart.prototype.ajaxPost = function (params) {97 this.throwUndefObj(params, 'ajaxPostParams');98 this.throwTypeError(params, 'object');99 this.throwUndefObj(params.url, 'ajaxPost.params.url');100 this.throwTypeError(params.url, 'string');101 params.method = 'POST';102 this.ajax(params);103};104WPCart.prototype.ajaxDelete = function (params) {105 this.throwUndefObj(params, 'ajaxDeleteParams');106 this.throwTypeError(params, 'object');107 this.throwUndefObj(params.url, 'ajaxDelete.params.url');108 this.throwTypeError(params.url, 'string');109 params.method = 'DELETE';110 this.ajax(params);111};112WPCart.prototype.getItems = function (callback) {113 this.throwUndefObj(callback, 'getItemsCallback');114 this.throwTypeError(callback, 'function');115 this.ajaxGet({116 url : this.baseAjaxUrl,117 success: callback118 });119};120WPCart.prototype.getItem = function(params, callback){121 this.throwUndefObj(params, 'getItemParams');122 this.throwTypeError(params, 'object');123 this.throwUndefObj(params.id, 'getItem.params.id');124 this.throwTypeError(params.id, 'Integer');125 this.throwUndefObj(callback, 'getItemCallback');126 this.throwTypeError(callback, 'function');127 this.ajaxGet({128 url : this.urlJoin([this.baseAjaxUrl, params.id]),129 success: callback,130 });131}132WPCart.prototype.addItem = function(params, callback){133 this.throwUndefObj(params, 'addItemParams');134 this.throwTypeError(params, 'object');135 this.throwUndefObj(params.id, 'addItems.params.id');136 this.throwTypeError(params.id, 'Integer');137 this.throwUndefObj(params.amount, 'addItem.params.amount');138 this.throwTypeError(params.amount, 'Integer');139 this.throwUndefObj(callback, 'addItemCallback');140 this.throwTypeError(callback, 'function');141 this.ajaxPost({142 url : this.baseAjaxUrl,143 success: callback,144 data: params145 });146};147WPCart.prototype.removeItem = function(params, callback){148 this.throwUndefObj(params, 'removeItemParams');149 this.throwTypeError(params, 'object');150 this.throwUndefObj(params.id, 'removeItem.params.id');151 this.throwTypeError(params.id, 'Integer');152 this.throwUndefObj(callback, 'removeItemCallback');153 this.throwTypeError(callback, 'function');154 this.ajaxDelete({155 url : this.urlJoin([this.baseAjaxUrl, params.id]),156 success: callback,157 });158};159WPCart.prototype.updateItem = function(params, callback){160 this.throwUndefObj(params, 'updateItemParams');161 this.throwTypeError(params, 'object');162 this.throwUndefObj(params.id, 'updateItem.params.id');163 this.throwTypeError(params.id, 'Integer');164 this.throwUndefObj(params.amount, 'updateItem.params.amount');165 this.throwTypeError(params.amount, 'Integer');166 this.throwUndefObj(callback, 'updateItemCallback');167 this.throwTypeError(callback, 'function');168 this.ajaxPost({169 url : this.urlJoin([this.baseAjaxUrl, params.id]),170 success: callback,171 data: {amount: params.amount}172 });173};174WPCart.prototype.clearItems = function(callback){175 this.throwUndefObj(callback, 'clearItemsCallback');176 this.throwTypeError(callback, 'function');177 this.ajaxDelete({178 url : this.baseAjaxUrl,179 success: callback,180 }); ...

Full Screen

Full Screen

client.js

Source:client.js Github

copy

Full Screen

1'use strict';2var _ = require('lodash');3var request = require('request');4var url = require('url');5var errors = require('./errors');6var requestExt = require('request-extensible');7Client.PACKAGE_VERSION = require('../package.json').version;8var resources = require('./resources');9Client.resources = resources;10/* Constructs the request which the client will use */11function getRequestLib(options) {12 var underlyingRequest = options.request || request;13 /* If extensions have been specified, use request-extensible */14 if (options.extensions) {15 return requestExt({16 request: underlyingRequest,17 extensions: options.extensions18 });19 }20 return underlyingRequest;21}22function Client(options) {23 if (!options) options = {};24 this.spread = options.spread;25 this.accessToken = options.accessToken;26 this.requestLib = getRequestLib(options);27 this.defaultHeaders = _.extend({28 'Accept': 'application/json',29 'Content-Type': 'application/json',30 'User-Agent': 'Tentacles/' + Client.PACKAGE_VERSION31 }, options.headers);32 this.anonymousClientId = options.anonymousClientId;33 this.anonymousClientSecret = options.anonymousClientSecret;34 this.clientId = options.clientId;35 this.clientSecret = options.clientSecret;36 this.errorHandler = options.errorHandler;37 this._prepResources();38}39Client.prototype = {40 _prepResources: function() {41 for (var name in resources) {42 var camelCaseName = name[0].toLowerCase() + name.substring(1);43 this[camelCaseName] = new resources[name](this);44 }45 },46 _request: function(method, path, data, spec, options) {47 var self = this;48 var headers = _.extend({}, this.defaultHeaders, spec.headers, options.headers);49 if (options.accessToken || this.accessToken) {50 headers.Authorization = 'token ' + (options.accessToken || this.accessToken);51 } else {52 // Use the anonymous application if set53 if (this.anonymousClientId && this.anonymousClientSecret) {54 if (!options.query) options.query = {};55 options.query.client_id = this.anonymousClientId;56 options.query.client_secret = this.anonymousClientSecret;57 }58 // Otherwise, use the default application, if set59 if (this.clientId && this.clientSecret) {60 if (!options.query) options.query = {};61 options.query.client_id = this.clientId;62 options.query.client_secret = this.clientSecret;63 }64 }65 var uri = url.format({66 protocol: "https:",67 host: "api.github.com",68 pathname: path,69 query: options.query70 });71 // Pass the options through to the extensions, but don't include the options72 // that have been mutated by this method73 var passThroughOptions = _.omit(options, 'query', 'accessToken', 'spread', 'headers', 'body', 'url', 'json', 'followRedirect', 'followAllRedirects');74 var requestOptions = _.defaults({75 method: method,76 uri: uri,77 headers: headers,78 body: data,79 json: !!data,80 gzip: true,81 encoding: options.encoding === undefined ? 'utf8' : options.encoding,82 followRedirect: true,83 followAllRedirects: true, // Redirects for non-GET requests84 }, passThroughOptions);85 var promise = new Client.Promise(function(resolve, reject) {86 function success(body, response) {87 if (options.spread === undefined ? self.spread : options.spread) {88 resolve([body, response]);89 } else {90 resolve(body);91 }92 }93 self.requestLib(requestOptions, function(err, response, body) {94 if (err) {95 err.response = response;96 return reject(err);97 }98 if (spec.checkOperation) {99 /* 404 means "false" */100 if (response.statusCode === 404) {101 return success(false, response);102 }103 /* 2XX means "true" */104 if (response.statusCode < 300) {105 return success(true, response);106 }107 }108 if (options.treat404asEmpty && response.statusCode === 404) {109 return success(null, response);110 }111 try {112 var parsedBody = self._parseBody(response, body);113 if (response.statusCode >= 400) {114 var message = typeof parsedBody.message === 'string' ? parsedBody.message.replace(/\n+/g, ' ') : "HTTP " + response.statusCode;115 return reject(new errors.TentaclesGitHubError(message, {116 url: uri,117 statusCode: response.statusCode,118 headers: response.headers,119 body: parsedBody || body120 }));121 }122 return success(parsedBody, response);123 } catch(e) {124 return reject(e);125 }126 });127 });128 /* Custom error handler */129 if (this.errorHandler) {130 return promise.catch(this.errorHandler);131 }132 return promise;133 },134 _parseBody: function(response, body) {135 if (typeof body !== 'string') return body;136 // TODO: deal with various types137 var contentType = response.headers['content-type'];138 if (contentType) {139 var ct = contentType.split(';')[0];140 if (ct === 'application/json') {141 return JSON.parse(body);142 }143 }144 return body;145 }146};147Client.Promise = require('bluebird');...

Full Screen

Full Screen

simple-proxy.js

Source:simple-proxy.js Github

copy

Full Screen

1/* eslint-disable no-console */2/* eslint-disable class-methods-use-this */3/* eslint-disable no-param-reassign */4const url = require('url');5const http = require('http');6const https = require('https');7const events = require('events');8class Proxy extends events.EventEmitter {9 constructor(proxyURI, options = {}) {10 super();11 this.logging = options.logging != null ? options.logging : false;12 this.timeout = options.timeout != null ? options.timeout : 0;13 this.agent = options.agent != null ? options.agent : undefined;14 this.preserveHost =15 options.preserveHost != null ? options.preserveHost : false;16 this.rejectUnauthorized =17 options.rejectUnauthorized != null ? options.rejectUnauthorized : true;18 const { protocol, hostname, port, pathname } = url.parse(proxyURI);19 this.protocol = protocol;20 this.hostname = hostname;21 this.port = port;22 // We concatenate with req.url later; no trailing slash is desired:23 this.pathname = pathname.replace(/\/$/, '');24 if (this.protocol === 'https:') {25 this.requestLib = https;26 if (!this.port) {27 this.port = 443;28 }29 } else if (this.protocol === 'http:') {30 this.requestLib = http;31 if (!this.port) {32 this.port = 80;33 }34 } else {35 throw new Error(`Unsupported protocol: ${this.protocol}`);36 }37 }38 server(req, res) {39 const options = {40 host: this.hostname,41 path: this.pathname + req.url,42 port: this.port,43 method: req.method,44 headers: req.headers,45 agent: this.agent,46 rejectUnauthorized: this.rejectUnauthorized,47 };48 if (!this.preserveHost) {49 options.headers.host = this.hostname;50 }51 const proxyRequest = this.requestLib.request(options, proxyResponse =>52 this.onProxyResponse(proxyResponse, res, options),53 );54 if (this.timeout) {55 proxyRequest.setTimeout(this.timeout, error => {56 error = `Request timed out after ${this.timeout} ms.`;57 this.emit('proxyTimeout', error, options);58 this.onProxyTimeout(error, options, res);59 proxyRequest.abort();60 });61 }62 proxyRequest.on('error', error => {63 this.emit('proxyError', error, options);64 this.onProxyError(error, options, res);65 });66 if (req.headers['content-length']) {67 this.processRequestData(proxyRequest, req, options);68 } else {69 proxyRequest.end();70 }71 }72 processRequestData(proxyRequest, req, options) {73 let requestData = '';74 req.on('data', chunk => {75 requestData += chunk;76 proxyRequest.write(chunk, 'binary');77 });78 req.on('end', () => {79 this.emit('requestEnd', requestData, options);80 proxyRequest.end();81 });82 }83 onProxyResponse(proxyResponse, res, options) {84 res.writeHead(proxyResponse.statusCode, proxyResponse.headers);85 let responseData = '';86 proxyResponse.on('data', chunk => {87 responseData += chunk;88 res.write(chunk, 'binary');89 });90 proxyResponse.on('end', () => {91 if (this.logging) {92 console.error(`Proxy end: ${responseData}`);93 }94 this.emit('proxyResponse', responseData, options);95 res.end();96 });97 }98 onProxyTimeout(err, options, res) {99 if (this.logging) {100 console.error(`Proxy timeout: ${err}`);101 }102 res.writeHead(504, 'Gateway Timeout');103 res.end();104 }105 onProxyError(err, options, res) {106 if (this.logging) {107 console.error(`Proxy error: ${err}, ${JSON.stringify(options)}`);108 }109 res.writeHead(502, 'Bad Gateway');110 res.end();111 }112}113function proxyPass(proxyURI, options = {}) {114 const p = new Proxy(proxyURI, options);115 return p.server.bind(p);116}117module.exports = {118 proxyPass,119 Proxy,...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const app = getApp()2const requestLib = require('../../../../api/request')3var UserData = require('../../../../api/userData')4const httpUrl = require('../../../../config')5const common = require('../../../../util/common.js')6Page({7 data: {8 // 此页面 页面内容距最顶部的距离9 height: app.globalData.navHeight * 2 + 19 ,10 // 组件所需的参数11 nvabarData: {12 showCapsule: 1, //是否显示左上角图标 1表示显示 0表示不显示13 title: '消息中心', //导航栏 中间的标题,14 isBackPer: true, //不显示返回按钮,15 bgColor:'#f4424a' //导航背景色16 },17 list:'',18 activeNames:'',19 20 },21 /**22 * 生命周期函数--监听页面加载23 */24 onLoad: function () {25 common.showLoading()26 this.getDataFun()27 },28 onShow: function () {29 if(!UserData || !UserData.get().token ){30 wx.redirectTo({31 url: '../../../../page/login/index'32 })33 }34 },35 // 获取数据36 getDataFun() {37 const wxs = this38 let data = {39 EmployeeId:UserData.get().id,40 Id: wxs.data.id,41 }42 requestLib.request({43 url: httpUrl.getMessages,44 method: 'post',45 data: data,46 success: successFun,47 fail: (error)=>{48 common.hideLoading()49 common.showToast(error.errMessage, 3000)50 }51 })52 function successFun(res){53 const resData = res.data54 if(resData && resData.code === 0){55 wxs.setData({56 list:resData.data57 })58 } else {59 common.showToast(error.errMessage, 3000)60 }61 common.hideLoading()62 }63 },64 onChange(e) {65 this.setData({66 activeNames: e.detail67 })68 let status = e.currentTarget.dataset.status69 if(!status){70 this.updateStatus(e.detail[0])71 }72 },73 updateStatus(data){74 const wxs = this75 requestLib.request({76 url: httpUrl.setMessageStatus,77 method: 'post',78 data: { messageId: data },79 success: successFun,80 fail: (error)=>{81 common.hideLoading()82 common.showToast(error.errMessage, 3000)83 }84 })85 function successFun(res){86 const resData = res.data87 if(resData && resData.code === 0){88 wxs.getDataFun()89 } else {90 common.showToast(error.errMessage, 3000)91 }92 common.hideLoading()93 }94 }...

Full Screen

Full Screen

Calculadora.js

Source:Calculadora.js Github

copy

Full Screen

1class Calculadora {2 constructor(number, requestLib) {3 this.value = number;4 this.requestLib = requestLib;5 }6 sum(value) {7 this.value += value;8 }9 result() {10 return this.value;11 }12 sub(value) {13 this.value -= value;14 }15 expression(fn) {16 this.value = fn(this.value);17 }18 readData() {19 return this.requestLib.get("http://teste.com.br/jao");20 }21}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import request from 'request';2Cypress.Commands.add('requestLib', (url) => {3 return new Cypress.Promise((resolve, reject) => {4 request(url, (error, response, body) => {5 if (error) {6 reject(error)7 } else {8 resolve(body)9 }10 })11 })12})13describe('Test', () => {14 it('should test', () => {15 .then((body) => {16 expect(body).to.contain('cy.readFile() - read a file')17 })18 })19})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('requestLib', (method, url, body) => {2 return cy.request({3 headers: {4 }5 });6});7{8 "env": {9 }10}11import './commands'12describe('My First Test', function() {13 it('Does not do much!', function() {14 cy.requestLib('GET', '/test')15 .its('body')16 .should('include', { success: true });17 });18});19Cypress.Commands.add('login', () => {20 cy.requestLib('POST', '/login', {21 username: Cypress.env('username'),22 password: Cypress.env('password')23 });24});25Cypress.Commands.add('logout', () => {26 cy.requestLib('POST', '/logout');27});28describe('My First Test', function() {29 it('Does not do much!', function() {30 cy.login();31 cy.requestLib('GET', '/test')32 .its('body')33 .should('include', { success: true });34 cy.logout();35 });36});37Cypress.Commands.add('login', () => {38 cy.requestLib('POST', '/login', {39 username: Cypress.env('username'),40 password: Cypress.env('password')41 });42});43Cypress.Commands.add('logout', () => {44 cy.requestLib('POST', '/logout');45});46describe('My First Test', function() {47 it('Does not do much!', function() {48 cy.login();49 cy.requestLib('GET', '/test')50 .its('body')

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 beforeEach(function() {3 })4 it('Does not do much!', function() {5 expect(true).to.equal(true)6 })7 it('Does not do much!', function() {8 })9})10Cypress.Commands.add('requestLib', (url, method, body, headers) => {11 const options = {12 }13 return cy.request(options)14})15import './commands'16{17}18{19 "scripts": {20 },21 "devDependencies": {22 }23}24describe('My First Test', function() {25 beforeEach(function() {26 })27 it('Does not do much!', function() {28 expect(true).to.equal(true)29 })30 it('Does not do much!', function() {31 })32})33describe('My First Test', function()

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 .its('body')4 .should('have.length', 1)5 })6})7describe('Notes app', function() {8 it('front page can be opened', function() {9 cy.contains('Notes')10 })11})12describe('Notes app', function() {13 it('front page can be opened', function() {14 cy.contains('Notes')15 })16})17describe('Notes app', function() {18 it('front page can be opened', function() {19 cy.contains('Notes')20 })21})22describe('Notes app', function() {23 it('front page can be opened', function() {24 cy.contains('Notes')25 })26})27describe('Notes app', function() {28 it('front page can be opened', function() {29 cy.contains('Notes')30 })31})32describe('Notes app', function() {33 it('front page can be opened', function() {34 cy.contains('Notes')35 })36})37describe('Notes app', function() {38 it('front page can be opened', function() {

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2Cypress.Commands.add('requestLib', (url, method, body) => {3 return request({4 })5})6describe('Sample Test', function () {7 it('Test Case', function () {8 cy.log(JSON.stringify(response))9 })10 })11})12{13 "env": {14 }15}16{17 "scripts": {18 },19 "devDependencies": {20 }21}22 * @type {Cypress.PluginConfig}23module.exports = (on, config) => {24}

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 expect(response.status).to.eq(200)4 console.log(response.body)5 })6 })7})8describe('My First Test', function() {9 it('Does not do much!', function() {10 expect(response.status).to.eq(200)11 console.log(response.body)12 })13 })14})15import { request } from 'cypress'16describe('My First Test', function() {17 it('Does not do much!', function() {18 expect(response.status).to.eq(200)19 console.log(response.body)20 })21 })22})23describe('My First Test', function() {24 it('Does not do much!', function() {25 expect(response.status).to.eq(200)26 console.log(response.body)27 })28 })29})30import { request } from 'cypress'31describe('My First Test', function() {32 it('Does not do much!', function() {

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test API', () => {2 it('Get API', () => {3 cy.request({4 }).then((response) => {5 cy.log(JSON.stringify(response.body))6 })7 })8})9{10 "requestLib": {11 }12}13describe('Test API', () => {14 it('Get API', () => {15 cy.request({16 }).then((response) => {17 cy.log(JSON.stringify(response.body))18 })19 })20})21describe('Test API', () => {22 it('Get API', () => {23 cy.request({24 }).then((response) => {25 cy.log(JSON.stringify(response.body))26 })27 })28})29describe('Test API', () => {30 it('Get API', () => {31 cy.request({32 }).then((response) => {33 cy.log(JSON.stringify(response.body))34 })35 })36})37describe('Test API', () => {

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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