Best JavaScript code snippet using playwright-internal
http-request.test.js
Source:http-request.test.js
1/*2 * NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)3 * Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.4 *5 * Distributed under the MIT license6 *7 * For the full copyright and license information, please view the LICENSE8 * file that was distributed with this source code9 *10 * @link https://github.com/kusanagi/katana-sdk-node11 * @license http://www.opensource.org/licenses/mit-license.php MIT License12 * @copyright Copyright (c) 2016-2018 KUSANAGI S.L. (http://kusanagi.io)13 */14'use strict';15const assert = require('assert');16const _ = require('lodash');17const url = require('url');18const HttpRequest = require('./http-request');19describe('HttpRequest', () => {20 const mockRequest = {21 version: '1.1',22 method: 'POST',23 url: 'http://example.com/v1.0.0/users'24 };25 it('should create an instance', () => {26 const httpRequest = new HttpRequest(mockRequest);27 assert.ok(httpRequest instanceof HttpRequest);28 });29 describe('isMethod()', () => {30 it('should determine if `method` matches that of the httpRequest', () => {31 const httpRequest = new HttpRequest(mockRequest);32 assert.ok(httpRequest.isMethod('POST'));33 });34 it('should return false if `method` does not math that of the httpRequest', () => {35 const httpRequest = new HttpRequest(mockRequest);36 assert.equal(httpRequest.isMethod('GET'), false);37 });38 });39 describe('getMethod()', () => {40 it('should return the httpRequest method', () => {41 const httpRequest = new HttpRequest(mockRequest);42 assert.equal(httpRequest.getMethod(), 'POST');43 });44 });45 describe('getUrl()', () => {46 it('should return the full URL provided for the httpRequest', () => {47 const httpRequest = new HttpRequest(mockRequest);48 assert.equal(httpRequest.getUrl(), mockRequest.url);49 });50 });51 describe('getUrlScheme()', () => {52 it('should return scheme used for the URL provided for the httpRequest', () => {53 const httpRequest = new HttpRequest(mockRequest);54 assert.equal(httpRequest.getUrlScheme(), url.parse(mockRequest.url).protocol);55 });56 });57 describe('getUrlHost()', () => {58 it('should return host of the URL provided for the httpRequest', () => {59 const httpRequest = new HttpRequest(mockRequest);60 assert.equal(httpRequest.getUrlHost(), url.parse(mockRequest.url).host);61 });62 });63 describe('getUrlPath()', () => {64 it('should return the path of the URL provided for the httpRequest', () => {65 const httpRequest = new HttpRequest(mockRequest);66 assert.equal(httpRequest.getUrlPath(), url.parse(mockRequest.url).pathname);67 });68 });69 describe('hasQueryParam()', () => {70 it('should determine if the paramater `name` exists in the query object', () => {71 const query = {q: ['test']};72 const _mockRequest = _.merge({query}, mockRequest);73 const httpRequest = new HttpRequest(_mockRequest);74 assert.ok(httpRequest.hasQueryParam('q'));75 });76 it('should throw if parameter `name` is not specified', () => {77 const httpRequest = new HttpRequest(mockRequest);78 assert.throws(httpRequest.hasQueryParam, /Specify a param `name`/);79 });80 });81 describe('getQueryParam()', () => {82 it('should return the value of the paramater by `name`', () => {83 const query = {q: ['test']};84 const _mockRequest = _.merge({query}, mockRequest);85 const httpRequest = new HttpRequest(_mockRequest);86 assert.deepEqual(httpRequest.getQueryParam('q'), query.q[0]);87 });88 it('should return the `defaultValue` if parameter `name` does not exist', () => {89 const query = {};90 const _mockRequest = _.merge({query}, mockRequest);91 const httpRequest = new HttpRequest(_mockRequest);92 assert.equal(httpRequest.getQueryParam('q', 'default'), 'default');93 });94 it('should throw if parameter `name` is not specified', () => {95 const httpRequest = new HttpRequest(mockRequest);96 assert.throws(httpRequest.getQueryParam, /Specify a param `name`/);97 });98 });99 describe('getQueryParamArray()', () => {100 it('should return the value of the paramater by `name` as an array', () => {101 const query = {q: ['test']};102 const _mockRequest = _.merge({query}, mockRequest);103 const httpRequest = new HttpRequest(_mockRequest);104 assert.deepEqual(httpRequest.getQueryParamArray('q'), query.q);105 });106 it('should return the `defaultValue` if parameter `name` does not exist', () => {107 const query = {};108 const _mockRequest = _.merge({query}, mockRequest);109 const httpRequest = new HttpRequest(_mockRequest);110 const defaultValue = ['default'];111 assert.deepEqual(httpRequest.getQueryParamArray('q', defaultValue), defaultValue);112 });113 it('should throw if parameter `name` is not specified', () => {114 const httpRequest = new HttpRequest(mockRequest);115 assert.throws(httpRequest.getQueryParamArray, /Specify a param `name`/);116 });117 it('should throw if `defaultValue` is not an array', () => {118 const httpRequest = new HttpRequest(mockRequest);119 assert.throws(() => httpRequest.getQueryParamArray('q', {}),120 /The `defaultValue` must be an array/);121 });122 it('should throw if `defaultValue` is not an array of strings', () => {123 const httpRequest = new HttpRequest(mockRequest);124 assert.throws(() => httpRequest.getQueryParamArray('q', ['', null]),125 /The `defaultValue` must be an array of strings/);126 });127 });128 xdescribe('getQueryParams()', () => {129 it('', () => {130 const httpRequest = new HttpRequest(mockRequest);131 assert.equal(httpRequest.getQueryParams(), mockRequest.url);132 });133 });134 describe('getQueryParamsArray()', () => {135 it('should return the query object', () => {136 const query = {q: ['test']};137 const _mockRequest = _.merge({query}, mockRequest);138 const httpRequest = new HttpRequest(_mockRequest);139 assert.deepEqual(httpRequest.getQueryParamsArray(), query);140 });141 });142 describe('hasPostParam()', () => {143 it('should determine if the parameter `name` is defined in the post data', () => {144 const postData = {name: ['test']};145 const _mockRequest = _.merge({postData}, mockRequest);146 const httpRequest = new HttpRequest(_mockRequest);147 assert.ok(httpRequest.hasPostParam('name'));148 });149 it('should throw if parameter `name` is not specified', () => {150 const httpRequest = new HttpRequest(mockRequest);151 assert.throws(httpRequest.hasPostParam, /Specify a param `name`/);152 });153 });154 describe('getPostParam()', () => {155 it('should return the value of the paramater by `name`', () => {156 const postData = {name: ['test']};157 const _mockRequest = _.merge({postData}, mockRequest);158 const httpRequest = new HttpRequest(_mockRequest);159 assert.deepEqual(httpRequest.getPostParam('name'), postData.name[0]);160 });161 it('should return the `defaultValue` if parameter `name` does not exist', () => {162 const postData = {};163 const _mockRequest = _.merge({postData}, mockRequest);164 const httpRequest = new HttpRequest(_mockRequest);165 assert.equal(httpRequest.getPostParam('name', 'default'), 'default');166 });167 it('should throw if parameter `name` is not specified', () => {168 const httpRequest = new HttpRequest(mockRequest);169 assert.throws(httpRequest.getPostParam, /Specify a param `name`/);170 });171 });172 describe('getPostParamArray()', () => {173 it('should return the value of the paramater by `name` as an array', () => {174 const postData = {name: ['test']};175 const _mockRequest = _.merge({postData}, mockRequest);176 const httpRequest = new HttpRequest(_mockRequest);177 assert.deepEqual(httpRequest.getPostParamArray('name'), postData.name);178 });179 it('should return the `defaultValue` if parameter `name` does not exist', () => {180 const postData = {};181 const _mockRequest = _.merge({postData}, mockRequest);182 const httpRequest = new HttpRequest(_mockRequest);183 const defaultValue = ['default'];184 assert.deepEqual(httpRequest.getPostParamArray('name', defaultValue), defaultValue);185 });186 it('should throw if parameter `name` is not specified', () => {187 const httpRequest = new HttpRequest(mockRequest);188 assert.throws(httpRequest.getPostParamArray, /Specify a param `name`/);189 });190 it('should throw if `defaultValue` is not an array', () => {191 const httpRequest = new HttpRequest(mockRequest);192 assert.throws(() => httpRequest.getPostParamArray('name', {}),193 /The `defaultValue` must be an array/);194 });195 it('should throw if `defaultValue` is not an array of strings', () => {196 const httpRequest = new HttpRequest(mockRequest);197 assert.throws(() => httpRequest.getPostParamArray('name', ['', null]),198 /The `defaultValue` must be an array of strings/);199 });200 });201 xdescribe('getPostParams()', () => {202 it('', () => {203 const httpRequest = new HttpRequest(mockRequest);204 assert.equal(httpRequest.getPostParams(), mockRequest.url);205 });206 });207 describe('getPostParamsArray()', () => {208 it('returns an object with the parameters provided in the post data', () => {209 const postData = {name: ['test']};210 const _mockRequest = _.merge({postData}, mockRequest);211 const httpRequest = new HttpRequest(_mockRequest);212 assert.deepEqual(httpRequest.getPostParamsArray(), postData);213 });214 });215 describe('getProtocolVersion()', () => {216 it('should get the protocol version', () => {217 const httpRequest = new HttpRequest(mockRequest);218 assert.equal(httpRequest.getProtocolVersion(), '1.1');219 });220 });221 describe('isProtocolVersion()', () => {222 it('should determine if protocol version matches', () => {223 const httpRequest = new HttpRequest(mockRequest);224 assert.ok(httpRequest.isProtocolVersion('1.1'));225 });226 it('should return false if versions do not match', () => {227 const httpRequest = new HttpRequest(mockRequest);228 assert.equal(httpRequest.isProtocolVersion('2.0'), false);229 });230 it('should throw an error if no version specified', () => {231 const httpRequest = new HttpRequest(mockRequest);232 assert.throws(httpRequest.isProtocolVersion, /Specify a protocol `version`/);233 });234 });235 describe('hasHeader()', () => {236 it('should determine if the httpRequest contains the specified header `name`', () => {237 const headers = {'Content-Type': 'test'};238 const _mockRequest = _.merge({headers}, mockRequest);239 const httpRequest = new HttpRequest(_mockRequest);240 assert.ok(httpRequest.hasHeader('Content-Type'));241 });242 it('should return false if the specified header does not exist', () => {243 const httpRequest = new HttpRequest(mockRequest);244 assert.equal(httpRequest.hasHeader('Content-Type'), false);245 });246 it('should throw an error if no header `name` specified', () => {247 const httpRequest = new HttpRequest(mockRequest);248 assert.throws(httpRequest.hasHeader, /Specify a header `name`/);249 });250 });251 describe('getHeader()', () => {252 it('should return the header with the specified `name`', () => {253 const headers = {'Content-Type': ['test']};254 const _mockRequest = _.merge({headers}, mockRequest);255 const httpRequest = new HttpRequest(_mockRequest);256 assert.equal(httpRequest.getHeader('Content-Type'), 'test');257 });258 it('should return the default value when header is not present', () => {259 const headers = {};260 const _mockRequest = _.merge({headers}, mockRequest);261 const httpRequest = new HttpRequest(_mockRequest);262 const defaultValue = 'text/plain';263 assert.equal(httpRequest.getHeader('Content-Type', defaultValue), defaultValue);264 });265 it('should throw an error if no header `name` specified', () => {266 const httpRequest = new HttpRequest(mockRequest);267 assert.throws(httpRequest.getHeader, /Specify a header `name`/);268 });269 });270 describe('getHeaderArray()', () => {271 it('should return the header array with the specified `name`', () => {272 const headers = {'Content-Type': ['test', 'tast']};273 const _mockRequest = _.merge({headers}, mockRequest);274 const httpRequest = new HttpRequest(_mockRequest);275 assert.deepEqual(httpRequest.getHeaderArray('Content-Type'), ['test', 'tast']);276 });277 it('should return the default value when header is not present', () => {278 const headers = {};279 const _mockRequest = _.merge({headers}, mockRequest);280 const httpRequest = new HttpRequest(_mockRequest);281 const defaultValue = 'text/plain';282 assert.deepEqual(httpRequest.getHeaderArray('Content-Type', defaultValue), defaultValue);283 });284 it('should return the empty array if no defaultValue is present', () => {285 const headers = {};286 const _mockRequest = _.merge({headers}, mockRequest);287 const httpRequest = new HttpRequest(_mockRequest);288 assert.deepEqual(httpRequest.getHeaderArray('Content-Type'), []);289 });290 it('should throw an error if no header `name` specified', () => {291 const httpRequest = new HttpRequest(mockRequest);292 assert.throws(httpRequest.getHeaderArray, /Specify a header `name`/);293 });294 });295 describe('getHeaders()', () => {296 it('should return all headers', () => {297 const headers = {'Content-Type': ['test', 'tast']};298 const _mockRequest = _.merge({headers}, mockRequest);299 const httpRequest = new HttpRequest(_mockRequest);300 assert.deepEqual(httpRequest.getHeaders(), {'Content-Type': 'test'});301 });302 it('should return an empty set of headers when none are set', () => {303 const httpRequest = new HttpRequest(mockRequest);304 assert.deepEqual(httpRequest.getHeaders(), {});305 });306 });307 describe('getHeaderArray()', () => {308 it('should return all headers as arrays', () => {309 const headers = {'Content-Type': ['test', 'tast']};310 const _mockRequest = _.merge({headers}, mockRequest);311 const httpRequest = new HttpRequest(_mockRequest);312 assert.deepEqual(httpRequest.getHeadersArray(), headers);313 });314 it('should return an empty set of headers when none are set', () => {315 const httpRequest = new HttpRequest(mockRequest);316 assert.deepEqual(httpRequest.getHeadersArray(), []);317 });318 });319 describe('hasBody()', () => {320 it('should determine if the HTTP httpRequest body contains content', () => {321 const body = ' ';322 const _mockRequest = _.merge({body}, mockRequest);323 const httpRequest = new HttpRequest(_mockRequest);324 assert.ok(httpRequest.hasBody());325 });326 it('should return false if HTTP httpRequest body does not exist', () => {327 const httpRequest = new HttpRequest(mockRequest);328 assert.equal(httpRequest.hasBody(), false);329 });330 });331 describe('getBody()', () => {332 it('should return the content of the HTTP httpRequest body', () => {333 const body = ' ';334 const _mockRequest = _.merge({body}, mockRequest);335 const httpRequest = new HttpRequest(_mockRequest);336 assert.deepEqual(httpRequest.getBody(), body);337 });338 it('should return an empty string if HTTP httpRequest body is not defined', () => {339 const httpRequest = new HttpRequest(mockRequest);340 assert.deepEqual(httpRequest.getBody(), '');341 });342 });343 describe('hasFile()', () => {344 it('should determine if the file was uploaded in the httpRequest by `name`', () => {345 const files = {avatar: {}};346 const _mockRequest = _.merge({files}, mockRequest);347 const httpRequest = new HttpRequest(_mockRequest);348 assert.ok(httpRequest.hasFile('avatar'));349 });350 it('should throw if file `name` is not specified', () => {351 const httpRequest = new HttpRequest(mockRequest);352 assert.throws(httpRequest.hasFile, /Specify a file `name`/);353 });354 it('should return false if the file was not uploaded in the httpRequest by `name`', () => {355 const httpRequest = new HttpRequest(mockRequest);356 assert.equal(httpRequest.hasFile('avatar'), false);357 });358 });359 xdescribe('getFile()', () => {360 it('', () => {361 const httpRequest = new HttpRequest(mockRequest);362 assert.equal(httpRequest.getFile(), mockRequest.url);363 });364 });365 describe('getFiles()', () => {366 it('should return an array with the files uploaded in the httpRequest', () => {367 const files = {avatar: {}};368 const _mockRequest = _.merge({files}, mockRequest);369 const httpRequest = new HttpRequest(_mockRequest);370 assert.deepEqual(httpRequest.getFiles('avatar'), files);371 });372 });...
store.js
Source:store.js
1import {httpStatusCodes} from "../../global";2import Account from "../../models/account";3import Order from "../../models/order";4const store = {5 reactComponent: null,6 account: _.assign(Object.create(Account), CR.ControllerData.account),7 config: CR.ControllerData.config,8 myToDos: [],9 otherOrders: [],10 allRaters: [],11 currentOrder: null,12 areMyToDosFetched: false,13 ordersSentToTheCustomerThisMonth: [],14 ordersToDo: [],15 init() {16 this._fetchMyToDos();17 this._fetchAllRaters();18 this._fetchStats();19 setInterval(() => {20 this._fetchStats();21 }, 10 * 1000);22 },23 assignOrderTo(account) {24 if (!this.currentOrder) {25 alert("Error: `this.currentOrder` must exist, this is a bug!");26 } else {27 const predicate = ["id", this.currentOrder.id];28 const order = _.find(this.myToDos, predicate) || _.find(this.otherOrders, predicate);29 order.rater = account;30 this.reactComponent.forceUpdate();31 const type = "PUT";32 const url = "/api/orders";33 const httpRequest = new XMLHttpRequest();34 httpRequest.onreadystatechange = () => {35 if (httpRequest.readyState === XMLHttpRequest.DONE) {36 if (httpRequest.status !== httpStatusCodes.ok) {37 alert(`AJAX failure doing a ${type} request to "${url}"`);38 }39 }40 };41 httpRequest.open(type, url);42 httpRequest.setRequestHeader("Content-Type", "application/json");43 httpRequest.send(JSON.stringify(order));44 }45 },46 deleteCurrentOrder() {47 if (!this.currentOrder) {48 alert("Error: `this.currentOrder` must exist, this is a bug!");49 } else {50 const orderId = this.currentOrder.id;51 const type = "DELETE";52 const url = `/api/orders/${orderId}`;53 const httpRequest = new XMLHttpRequest();54 httpRequest.onreadystatechange = () => {55 if (httpRequest.readyState === XMLHttpRequest.DONE) {56 if (httpRequest.status === httpStatusCodes.ok) {57 const predicate = o => o.id === orderId;58 _.remove(this.myToDos, predicate);59 _.remove(this.otherOrders, predicate);60 this.reactComponent.forceUpdate();61 } else {62 alert(`AJAX failure doing a ${type} request to "${url}"`);63 }64 }65 };66 httpRequest.open(type, url);67 httpRequest.send();68 }69 },70 fetchTeamOrders() {71 const type = "POST";72 const url = "/api/orders/team";73 const httpRequest = new XMLHttpRequest();74 httpRequest.onreadystatechange = () => {75 if (httpRequest.readyState === XMLHttpRequest.DONE) {76 if (httpRequest.status === httpStatusCodes.ok) {77 const ordersJson = JSON.parse(httpRequest.responseText);78 this.otherOrders = ordersJson.map(o => _.assign(Object.create(Order), o));79 this.reactComponent.forceUpdate();80 this._fetchLastRatingInfoForDisplayedCustomers();81 } else {82 alert(`AJAX failure doing a ${type} request to "${url}"`);83 }84 }85 };86 httpRequest.open(type, url);87 httpRequest.setRequestHeader("Content-Type", "application/json");88 httpRequest.send(JSON.stringify(this.myToDos.map(order => order.id)));89 },90 fetchMoreOrders(onAjaxRequestDone) {91 this._updateSearchCriteria();92 const type = "POST";93 const url = "/api/orders/completed";94 const httpRequest = new XMLHttpRequest();95 httpRequest.onreadystatechange = () => {96 if (httpRequest.readyState === XMLHttpRequest.DONE) {97 onAjaxRequestDone();98 if (httpRequest.status === httpStatusCodes.ok) {99 const ordersJson = JSON.parse(httpRequest.responseText);100 const orders = ordersJson.map(o => _.assign(Object.create(Order), o));101 this.otherOrders = _.concat(this.otherOrders, orders);102 this.reactComponent.forceUpdate();103 this._fetchLastRatingInfoForDisplayedCustomers();104 } else {105 alert(`AJAX failure doing a ${type} request to "${url}"`);106 }107 }108 };109 httpRequest.open(type, url);110 httpRequest.setRequestHeader("Content-Type", "application/json");111 httpRequest.send(JSON.stringify({112 from: this.searchCriteria.fromMoment ? this.searchCriteria.fromMoment.valueOf() : null,113 to: this.searchCriteria.toMoment.valueOf()114 }));115 },116 isOrderReadOnly(order) {117 if (order.rater && order.rater.id === this.account.id && order.status === Order.statuses.paid) {118 return false;119 }120 return order.isReadOnly(this.account);121 },122 isOrderDuplicate(order) {123 const duplicateOrder = _.find(this.myToDos, o => o.id !== order.id && o.customer.id === order.customer.id) ||124 _.find(this.otherOrders, o => o.id !== order.id && o.customer.id === order.customer.id && o.status !== Order.statuses.completed);125 return duplicateOrder !== undefined; // eslint-disable-line no-undefined126 },127 _fetchMyToDos() {128 const type = "GET";129 const url = "/api/orders/my-todo";130 const httpRequest = new XMLHttpRequest();131 httpRequest.onreadystatechange = () => {132 if (httpRequest.readyState === XMLHttpRequest.DONE) {133 if (httpRequest.status === httpStatusCodes.ok) {134 const myToDosJson = JSON.parse(httpRequest.responseText);135 this.myToDos = myToDosJson.map(o => _.assign(Object.create(Order), o));136 this.areMyToDosFetched = true;137 this.reactComponent.forceUpdate();138 } else {139 alert(`AJAX failure doing a ${type} request to "${url}"`);140 }141 }142 };143 httpRequest.open(type, url);144 httpRequest.send();145 },146 _fetchAllRaters() {147 const type = "GET";148 const url = "/api/accounts/raters";149 const httpRequest = new XMLHttpRequest();150 httpRequest.onreadystatechange = () => {151 if (httpRequest.readyState === XMLHttpRequest.DONE) {152 if (httpRequest.status === httpStatusCodes.ok) {153 const allRatersJson = JSON.parse(httpRequest.responseText);154 this.allRaters = allRatersJson.map(o => _.assign(Object.create(Account), o));155 this.reactComponent.forceUpdate();156 } else {157 alert(`AJAX failure doing a ${type} request to "${url}"`);158 }159 }160 };161 httpRequest.open(type, url);162 httpRequest.send();163 },164 _fetchStats() {165 this._fetchOrdersToDo();166 this._fetchOrdersSentToTheCustomerThisMonth();167 },168 _fetchOrdersToDo() {169 const type = "GET";170 const url = "/api/orders/stats/todo";171 const httpRequest = new XMLHttpRequest();172 httpRequest.onreadystatechange = () => {173 if (httpRequest.readyState === XMLHttpRequest.DONE) {174 if (httpRequest.status === httpStatusCodes.ok) {175 const ordersToDoJson = JSON.parse(httpRequest.responseText);176 this.ordersToDo = ordersToDoJson.map(o => _.assign(Object.create(Order), o));177 // No need to `reactComponent.forceUpdate`, as `_fetchOrdersSentToTheCustomerThisMonth()` does it already.178 } else {179 // We don't display any error, because this call happens often, and possibly on page refresh180 // alert(`AJAX failure doing a ${type} request to "${url}"`);181 }182 }183 };184 httpRequest.open(type, url);185 httpRequest.send();186 },187 _fetchOrdersSentToTheCustomerThisMonth() {188 const type = "GET";189 const url = "/api/orders/stats/sent";190 const httpRequest = new XMLHttpRequest();191 httpRequest.onreadystatechange = () => {192 if (httpRequest.readyState === XMLHttpRequest.DONE) {193 if (httpRequest.status === httpStatusCodes.ok) {194 const sentOrdersJson = JSON.parse(httpRequest.responseText);195 this.ordersSentToTheCustomerThisMonth = sentOrdersJson.map(o => _.assign(Object.create(Order), o));196 this.reactComponent.forceUpdate();197 } else {198 // We don't display any error, because this call happens often, and possibly on page refresh199 // alert(`AJAX failure doing a ${type} request to "${url}"`);200 }201 }202 };203 httpRequest.open(type, url);204 httpRequest.send();205 },206 _updateSearchCriteria() {207 if (!this.searchCriteria) {208 this.searchNbDays = 60;209 this.searchCriteria = {210 toMoment: moment().subtract(this.searchNbDays, "day")211 };212 } else {213 this.searchCriteria.fromMoment = moment(this.searchCriteria.toMoment);214 this.searchNbDays *= 2;215 this.searchCriteria.toMoment.subtract(this.searchNbDays, "day");216 }217 },218 _fetchLastRatingInfoForDisplayedCustomers() {219 const type = "POST";220 const url = "/api/assessments/scores-of-customers";221 const httpRequest = new XMLHttpRequest();222 httpRequest.onreadystatechange = () => {223 if (httpRequest.readyState === XMLHttpRequest.DONE) {224 if (httpRequest.status === httpStatusCodes.ok) {225 /*226 * {227 * 646: [228 * {229 * order: {},230 * scores: {231 * cvReportScores: {},232 * coverLetterReportScores: {},233 * linkedinProfileReportScores: {}234 * }235 * }, {236 * order: {},237 * scores: {238 * cvReportScores: {}239 * }240 * }],241 * 886: [...]242 * }243 */244 const customerIdsAndTheirOrdersAndScores = JSON.parse(httpRequest.responseText);245 this.customerIdsAndTheirOrdersAndScores = {};246 for (const customerId of _.keys(customerIdsAndTheirOrdersAndScores)) {247 const customerOrdersAndScores = customerIdsAndTheirOrdersAndScores[customerId].map(orderAndScores => {248 const smartOrder = _.assign(Object.create(Order), orderAndScores.order);249 return {250 order: smartOrder,251 scores: orderAndScores.scores252 };253 });254 this.customerIdsAndTheirOrdersAndScores[customerId] = customerOrdersAndScores;255 }256 this.reactComponent.forceUpdate();257 } else {258 alert(`AJAX failure doing a ${type} request to "${url}"`);259 }260 }261 };262 httpRequest.open(type, url);263 httpRequest.setRequestHeader("Content-Type", "application/json");264 httpRequest.send(JSON.stringify(this._currentCustomerIds()));265 },266 _currentCustomerIds() {267 const customerIds = [];268 for (const order of this.myToDos) {269 customerIds.push(order.customer.id);270 }271 for (const order of this.otherOrders) {272 customerIds.push(order.customer.id);273 }274 return _.uniq(customerIds);275 }276};...
script_option.js
Source:script_option.js
1document.getElementsByTagName('body');2window.onload=init();3function init(){4 console.log("init");5}6function requeteMessenger(param,callBack){7 var httpRequest = new XMLHttpRequest();8 var url="https://api.twitch.tv/helix/streams?user_login="+param;9 httpRequest.open("GET", url, true);10 var key ="";11 httpRequest.setRequestHeader('Client-ID',key);12 httpRequest.setRequestHeader("Content-Type", "application/json");13 httpRequest.addEventListener("load", function () {14 callBack(httpRequest,nomChaine);15 });16 httpRequest.send();17}18function requeteFacebook(param,callBack){19 var httpRequest = new XMLHttpRequest();20 var url="https://api.twitch.tv/helix/streams?user_login="+param;21 httpRequest.open("GET", url, true);22 var key ="";23 httpRequest.setRequestHeader('Client-ID',key);24 httpRequest.setRequestHeader("Content-Type", "application/json");25 httpRequest.addEventListener("load", function () {26 callBack(httpRequest,nomChaine);27 });28 httpRequest.send();29}30function requeteTwitter(param,callBack){31 var httpRequest = new XMLHttpRequest();32 var url="https://api.twitch.tv/helix/streams?user_login="+param;33 httpRequest.open("GET", url, true);34 var key ="";35 httpRequest.setRequestHeader('Client-ID',key);36 httpRequest.setRequestHeader("Content-Type", "application/json");37 httpRequest.addEventListener("load", function () {38 callBack(httpRequest,nomChaine);39 });40 httpRequest.send();41}42function requeteTwitterMessanger(param,callBack){43 var httpRequest = new XMLHttpRequest();44 var url="https://api.twitch.tv/helix/streams?user_login="+param;45 httpRequest.open("GET", url, true);46 var key ="";47 httpRequest.setRequestHeader('Client-ID',key);48 httpRequest.setRequestHeader("Content-Type", "application/json");49 httpRequest.addEventListener("load", function () {50 callBack(httpRequest,nomChaine);51 });52 httpRequest.send();53}54function requeteInstagram(param,callBack){55 var httpRequest = new XMLHttpRequest();56 var url="https://api.twitch.tv/helix/streams?user_login="+param;57 httpRequest.open("GET", url, true);58 var key ="";59 httpRequest.setRequestHeader('Client-ID',key);60 httpRequest.setRequestHeader("Content-Type", "application/json");61 httpRequest.addEventListener("load", function () {62 callBack(httpRequest,nomChaine);63 });64 httpRequest.send();65}66function requeteInstagramMessaging(param,callBack){67 var httpRequest = new XMLHttpRequest();68 var url="https://api.twitch.tv/helix/streams?user_login="+param;69 httpRequest.open("GET", url, true);70 var key ="";71 httpRequest.setRequestHeader('Client-ID',key);72 httpRequest.setRequestHeader("Content-Type", "application/json");73 httpRequest.addEventListener("load", function () {74 callBack(httpRequest,nomChaine);75 });76 httpRequest.send();77}78function requeteWebtoon(param,callBack){79 var httpRequest = new XMLHttpRequest();80 var url="https://api.twitch.tv/helix/streams?user_login="+param;81 httpRequest.open("GET", url, true);82 var key ="";83 httpRequest.setRequestHeader('Client-ID',key);84 httpRequest.setRequestHeader("Content-Type", "application/json");85 httpRequest.addEventListener("load", function () {86 callBack(httpRequest,nomChaine);87 });88 httpRequest.send();89}90function requeteSongKick(param,callBack){91 var httpRequest = new XMLHttpRequest();92 var url="https://api.twitch.tv/helix/streams?user_login="+param;93 httpRequest.open("GET", url, true);94 var key ="";95 httpRequest.setRequestHeader('Client-ID',key);96 httpRequest.setRequestHeader("Content-Type", "application/json");97 httpRequest.addEventListener("load", function () {98 callBack(httpRequest,nomChaine);99 });100 httpRequest.send();...
note.js
Source:note.js
1let ajax = {2 ajaxMethod:'POST',3 select:function (id){4 var formData = new FormData()5 formData.append('id', id)6// ajax method without jquery7 var httpRequest = new XMLHttpRequest()8 httpRequest.open(this.ajaxMethod, '/view-note/')9 httpRequest.send(formData);10 httpRequest.onreadystatechange = function() {11 // Process the server response here.12 if (httpRequest.readyState === XMLHttpRequest.DONE) {13 if (httpRequest.status === 200) {14 let result = JSON.parse(httpRequest.responseText)15 document.querySelector("#info").innerHTML = "<h4>"+result.subject+"</h4><br/>"+ result.content16 } else {17 message('error','There was a problem with the request.')18 }19 }20 }21 },22 Done:function (id){23 var formData = new FormData()24 formData.append('id', id)25// ajax method without jquery26 var httpRequest = new XMLHttpRequest()27 httpRequest.open(this.ajaxMethod, '/note-do-it/')28 httpRequest.send(formData);29 httpRequest.onreadystatechange = function() {30 // Process the server response here.31 if (httpRequest.readyState === XMLHttpRequest.DONE) {32 if (httpRequest.status === 200) {33 location.reload()34 } else {35 // message('error','There was a problem with the request.')36 }37 }38 }39 },40 Delete:function (id){41 var formData = new FormData()42 formData.append('id', id)43// ajax method without jquery44 var httpRequest = new XMLHttpRequest()45 httpRequest.open(this.ajaxMethod, '/note-delete/')46 httpRequest.send(formData);47 httpRequest.onreadystatechange = function() {48 // Process the server response here.49 if (httpRequest.readyState === XMLHttpRequest.DONE) {50 if (httpRequest.status === 200) {51 message("success","Delete successfully")52 setTimeout(function () {53 location.reload()54 },500)55 } else {56 message('error','There was a problem with the request.')57 }58 }59 }60 },61}62function message(type,message)63{64 var Toast = Swal.mixin({65 toast: true,66 position: 'top-end',67 showConfirmButton: false,68 timer: 300069 });70 if(type=='success'){71 Toast.fire({72 icon: 'success',73 title: message74 })75 }else if(type=='error'){76 Toast.fire({77 icon: 'error',78 title: message79 })80 }81}82function infoCome(id)83{84 ajax.select(id)...
httprequest.js
Source:httprequest.js
1// Copyright 2007 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview This file contains functions for setting up the standard16 * goog.net.XmlHttp factory (and, therefore, goog.net.XhrIo) to work using17 * the HttpRequest object Gears provides.18 *19 */20goog.provide('goog.gears.HttpRequest');21goog.require('goog.Timer');22goog.require('goog.gears');23goog.require('goog.net.WrapperXmlHttpFactory');24goog.require('goog.net.XmlHttp');25/**26 * Sets up the Gears HttpRequest's to be the default HttpRequest's used via27 * the goog.net.XmlHttp factory.28 */29goog.gears.HttpRequest.setup = function() {30 // Set the XmlHttp factory.31 goog.net.XmlHttp.setGlobalFactory(32 new goog.net.WrapperXmlHttpFactory(33 goog.gears.HttpRequest.factory_,34 goog.gears.HttpRequest.optionsFactory_));35 // Use the Gears timer as the default timer object to ensure that the XhrIo36 // timeouts function in the Workers.37 goog.Timer.defaultTimerObject = goog.gears.getFactory().create(38 'beta.timer', '1.0');39};40/**41 * The factory for creating Gears HttpRequest's.42 * @return {!(GearsHttpRequest|XMLHttpRequest)} The request object.43 * @private44 */45goog.gears.HttpRequest.factory_ = function() {46 return goog.gears.getFactory().create('beta.httprequest', '1.0');47};48/**49 * The options object for the Gears HttpRequest.50 * @type {!Object}51 * @private52 */53goog.gears.HttpRequest.options_ = {};54// As of Gears API v.2 (build version 0.1.56.0), setting onreadystatechange to55// null in FF will cause the browser to crash.56goog.gears.HttpRequest.options_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] =57 true;58/**59 * The factory for creating the options object for Gears HttpRequest's.60 * @return {!Object} The options.61 * @private62 */63goog.gears.HttpRequest.optionsFactory_ = function() {64 return goog.gears.HttpRequest.options_;...
jrefresh.js
Source:jrefresh.js
1function imgrequest( url, el )2{3 var httpRequest;4 try { httpRequest = new XMLHttpRequest(); }5 catch (trymicrosoft) { try { httpRequest = new ActiveXObject('Msxml2.XMLHTTP'); } catch (oldermicrosoft) { try { httpRequest = new ActiveXObject('Microsoft.XMLHTTP'); } catch(failed) { httpRequest = false; } } }6 if (!httpRequest) { alert('Your browser does not support Ajax.'); return false; }7 if ( typeof(el)!='undefined' ) {8 el.onclick = null;9 el.style.opacity = '0.7';10 httpRequest.onreadystatechange = function()11 {12 if (httpRequest.readyState == 4) if (httpRequest.status == 200) el.style.opacity = '0.3';13 }14 }15 httpRequest.open('GET', url, true);16 httpRequest.send(null);17}18var autorefresh=3000;19var tautorefresh;20function setautorefresh(t)21{22 clearTimeout(tautorefresh);23 autorefresh = t;24 if (t>0) tautorefresh = setTimeout('updateDiv()',autorefresh);25}26function updateDiv()27{28 var httpRequest;29 try {30 httpRequest = new XMLHttpRequest();31 }32 catch(trymicrosoft) {33 try {34 httpRequest = new ActiveXObject('Msxml2.XMLHTTP');35 }36 catch(oldermicrosoft) {37 try {38 httpRequest = new ActiveXObject('Microsoft.XMLHTTP');39 }40 catch(failed) {41 httpRequest = false;42 }43 }44 }45 if (!httpRequest) {46 alert('Your browser does not support Ajax.');47 return false;48 }49 httpRequest.onreadystatechange = function()50 {51 if (httpRequest.readyState == 4) {52 if(httpRequest.status == 200) {53 requestError=0;54 document.getElementById('wrapper').innerHTML = httpRequest.responseText;55 }56 tautorefresh = setTimeout('updateDiv()',autorefresh);57 }58 }59 httpRequest.open('GET', '/?action=div', true);60 httpRequest.send(null);61}62function start()63{64 setautorefresh(autorefresh);...
request.js
Source:request.js
1const getCookie = (name) => {2 const value = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');3 return value? value[2] : null;4};5const sendRequest = (url, callback) => {6 const httpRequest = new XMLHttpRequest();7 httpRequest.open('GET', url);8 httpRequest.withCredentials = true;9 httpRequest.send();10 httpRequest.onreadystatechange = () => {11 if (httpRequest.readyState === XMLHttpRequest.DONE) {12 if (httpRequest.status === 200 || httpRequest.status === 201) {13 const response = JSON.parse(httpRequest.response);14 callback(response);15 } 16 else {17 console.log(httpRequest.status);18 }19 }20 21 }22};23const sendPostRequest = (url, requestBody, callback) => {24 const csrftoken = getCookie('csrftoken');25 const httpRequest = new XMLHttpRequest();26 httpRequest.open('POST', url);27 httpRequest.withCredentials = true;28 httpRequest.setRequestHeader('X-CSRFTOKEN', csrftoken);29 httpRequest.send(JSON.stringify(requestBody));30 httpRequest.onreadystatechange = () => {31 32 if (httpRequest.readyState === XMLHttpRequest.DONE) {33 if (httpRequest.status === 200 || httpRequest.status === 201) {34 callback();35 } else {36 console.log(httpRequest.status);37 }38 39 }40 }...
aws-sdk.js
Source:aws-sdk.js
1export function initialize(application) {2 // Monkey patch AWS SDK to go through our proxy3 var orig = AWS.XHRClient.prototype.handleRequest;4 AWS.XHRClient.prototype.handleRequest = function handleRequest(httpRequest, httpOptions, callback, errCallback) {5 httpRequest.endpoint.protocol = 'http:';6 httpRequest.endpoint.port = 80;7 httpRequest.headers['X-API-Headers-Restrict'] = 'Content-Length';8 httpRequest.headers['X-API-AUTH-HEADER'] = httpRequest.headers['Authorization'];9 httpRequest.headers['Content-Type'] = 'rancher:' + httpRequest.headers['Content-Type'];10 var endpoint = application.proxyEndpoint+'/';11 if ( httpRequest.path.indexOf(endpoint) !== 0 )12 {13 httpRequest.path = endpoint + httpRequest.endpoint.hostname + httpRequest.path;14 }15 httpRequest.endpoint.protocol = window.location.protocol;16 httpRequest.endpoint.hostname = window.location.hostname;17 httpRequest.endpoint.host = window.location.host;18 httpRequest.endpoint.port = window.location.port;19 return orig.call(this, httpRequest, httpOptions, callback, errCallback);20 };21}22export default {23 name: 'aws-sdk',24 initialize: initialize...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright['chromium'].launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const request = await response.request();7 const response2 = await request.response();8 console.log(response2.status());9 await browser.close();10})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const response = await page.route('**/api/**', route => {7 route.fulfill({8 headers: {9 },10 body: JSON.stringify({ foo: 'bar' }),11 });12 });13 await browser.close();14})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!