Best JavaScript code snippet using cypress
server.js
Source:server.js
...228}229/**230 * sets headers for current response according to default settings231 */232function setDefaultHeaders(status, request, response) {233 response.writeHead(status, {234 'Access-Control-Allow-Origin' : DEFAULT_ACCESS_CONTROL,235 'Content-Type' : mimeTypeParser(request, response)236 });237}238/**239 * Checks passed requests for a defined file Mime Type.240 *241 * @return {String} requestMimeType a file mimetype of current request if defined, or a default .txt mime type 242 * if request's mime type is not defined243 */244function mimeTypeParser(request, response) {245 var requestToHandle = requestRouter(request, response);246 var requestMimeType = dictionaryOfMimeTypes['txt'];247 if(typeof requestToHandle == 'function') {248 requestToHandle = request.url;249 }250 // retrieve file extension from current request by grabbing251 // suffix after last period of request string252 var requestFileExtension = requestToHandle.split('.');253 requestFileExtension = requestFileExtension[requestFileExtension.length - 1];254 requestFileExtension = requestFileExtension.split('&')[0];255 if(dictionaryOfMimeTypes.hasOwnProperty(requestFileExtension)) {256 requestMimeType = dictionaryOfMimeTypes[requestFileExtension];257 }258 return requestMimeType;259}260/**261 * Serves current request as a stream from a file on the server262 */263function handleRequestAsFileStream(request, response) {264 var requestToHandle = requestRouter(request, response);265 fs.readFile(__dirname + '/' + requestToHandle, function(error, data) {266 if(error) {267 console.log('File ' + requestToHandle + ' could not be served -> ' + error);268 269 setDefaultHeaders(SERVER_HEAD_NOTFOUND, request, response);270 response.end(SERVER_RES_NOTFOUND);271 }272 setDefaultHeaders(SERVER_HEAD_OK, request, response);273 response.end(data);274 });275}276/**277 * Serves current request along with data from a specified api uri278 */279function handleRequestAsAPICall(request, response) {280 var APIURI = request.url.split('/api/')[1];281 var APIResponseData = '';282 if(APIURI == '') {283 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);284 return response.end(SERVER_RES_ERROR);285 }286 https.get(APIURI, function(APIResponse) {287 APIResponse.on('data', function(chunk) {288 APIResponseData += chunk;289 });290 APIResponse.on('end', function() {291 setDefaultHeaders(SERVER_HEAD_OK, request, response);292 response.end(APIResponseData);293 });294 }).on('error', function(error) {295 console.log('<HTTP.Get> ' + error.message);296 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);297 response.end(APIURI);298 });299}300/**301 * POSTs current api request to endpoint uri and returns response to client302 */303function handleRequestAsAPIPOSTCall(request, response) {304 var APIURI = request.url.split('/api/post/')[1];305 var URIComponents = url.parse(APIURI);306 var POSTDataFromClient = '';307 var APIResponseData = '';308 if(APIURI == '') {309 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);310 return response.end(SERVER_RES_ERROR);311 }312 // receive data to relay from client313 request.on('data', function(chunk) {314 POSTDataFromClient += chunk;315 });316 request.on('end', function() {317 var APIPostRequest = https.request({318 host : URIComponents.host,319 path : URIComponents.path,320 href : URIComponents.href,321 method : 'POST',322 headers : {323 'Content-Type' : request.headers['content-type']324 }325 }, function(APIResponse) {326 APIResponse.on('data', function(chunk) {327 APIResponseData += chunk;328 });329 APIResponse.on('end', function() {330 response.writeHead(SERVER_HEAD_OK, {331 'Access-Control-Allow-Origin' : '*',332 'Content-Type' : 'text/html'333 334 });335 console.log(APIResponseData);336 response.end(APIResponseData);337 });338 }).end(POSTDataFromClient);339 });340}341/**342 * handles requets as receiving data with GET method343 */344function handleRequestAsGETEndpoint(request, response) {345 var requestIntent = request.url.split('/');346 var JSONResponse = {347 status : 200,348 success: true349 };350 351 if(requestIntent[2] == 'item') {352 // search query is being sent353 if(requestIntent[3] == 'keyword') {354 var query = requestIntent[4];355 database.selectFrom('items', '*', "itemName LIKE '%" + query + "%' OR category LIKE '%" + query + "%' OR keywords LIKE '%" + query + "%'", function(error, rows, columns) {356 if(error) {357 var errorResponse = '<MySQL> An error occurred fetching data from the database';358 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);359 response.end(errorResponse);360 return console.log(errorResponse);361 }362 JSONResponse.results = rows;363 setDefaultHeaders(SERVER_HEAD_OK, request, response);364 response.end(JSON.stringify(JSONResponse));365 });366 } else if(requestIntent[3] == 'id') {367 var query = requestIntent[4];368 database.selectFrom('items', '*', "itemId='" + query + "'", function(error, rows, columns) {369 if(error) {370 var errorResponse = '<MySQL> An error occurred fetching data from the database';371 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);372 response.end(errorResponse);373 return console.log(errorResponse);374 }375 JSONResponse.results = rows;376 setDefaultHeaders(SERVER_HEAD_OK, request, response);377 response.end(JSON.stringify(JSONResponse));378 });379 } else {380 setDefaultHeaders(SERVER_HEAD_OK, request, response);381 response.end(JSON.stringify(JSONResponse));382 383 }384 } else if(requestIntent[2] == 'user') {385 // search query is being sent386 if(requestIntent[3] == 'id') {387 var query = requestIntent[4];388 database.selectFrom('users', '*', 'userId="' + query + '"', function(error, rows, columns) {389 if(error) {390 var errorResponse = '<MySQL> An error occurred fetching data from the database';391 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);392 response.end(errorResponse);393 return console.log(errorResponse);394 }395 JSONResponse.results = rows;396 setDefaultHeaders(SERVER_HEAD_OK, request, response);397 response.end(JSON.stringify(JSONResponse));398 });399 } else {400 setDefaultHeaders(SERVER_HEAD_OK, request, response);401 response.end(JSON.stringify(JSONResponse));402 }403 } else {404 setDefaultHeaders(SERVER_HEAD_OK, request, response);405 response.end(JSON.stringify(JSONResponse));406 }407}408/**409 * handles requets as receiving data with POST method to endpoint /action/*410 */411function handleRequestAsPOSTEndpoint(request, response) {412 // if(request.method != 'POST') {413 // setDefaultHeaders(SERVER_HEAD_ERROR, request, response);414 // return response.end(SERVER_RES_POST_ERROR);415 // }416 var requestIntent = request.url.split('/');417 var postData = '';418 request.on('data', function(chunk) {419 postData += chunk;420 });421 request.on('end', function() {422 try {423 // parse response as a JSON object.424 var parsedPostData = JSON.parse(postData);425 console.log('<~400: Post data received> ' + postData);426 // default JSON response427 var JSONResponse = {428 429 status : 200,430 success : true,431 error : false432 };433 // login endpoint reached434 if(requestIntent[1] == 'login') {435 // check to see that the required parameters exist436 if(parsedPostData.username && parsedPostData.password) {437 setDefaultHeaders(SERVER_HEAD_OK, request, response);438 database.selectFrom('users', '*', 'username="' + parsedPostData.username + '"', function(error, rows, columns) {439 // check for database error440 if(error) {441 JSONResponse.staus = SERVER_HEAD_ERROR;442 JSONResponse.error = '<MySQL> An error occurred fetching data from the database -> ' + error;443 JSONResponse.success = false;444 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);445 response.end(JSON.stringify(JSONResponse));446 return console.log(JSONResponse.error);447 }448 // check to see if any records exist with username provided449 if(rows.length <= 0 || (rows[0].username != parsedPostData.username || rows[0].password != parsedPostData.password)) {450 JSONResponse.staus = SERVER_HEAD_AUTH_ERROR;451 JSONResponse.error = '<MySQL> A user with the username ' + parsedPostData.username + ' does not exist';452 JSONResponse.success = false;453 setDefaultHeaders(SERVER_HEAD_AUTH_ERROR, request, response);454 response.end(JSON.stringify(JSONResponse));455 return console.log(JSONResponse.error);456 }457 // login successful458 JSONResponse.data = rows[0];459 setDefaultHeaders(SERVER_HEAD_OK, request, response);460 response.end(JSON.stringify(JSONResponse));461 });462 } else {463 setDefaultHeaders(SERVER_HEAD_AUTH_ERROR, request, response);464 JSONResponse.status = SERVER_HEAD_AUTH_ERROR;465 JSONResponse.success = false;466 JSONResponse.error = 'Invalid parameters sent.';467 response.end(JSON.stringify(JSONResponse));468 }469 } else if(requestIntent[1] == 'put') {470 setDefaultHeaders(SERVER_HEAD_NOTFOUND);471 response.end(JSON.stringify(JSONResponse));472 } else {473 response.end(JSON.stringify(JSONResponse));474 }475 } catch(exception) {476 var errorResponse = '<~400: Exception> The post data received from the client is not formatted as JSON.';477 478 console.log(errorResponse);479 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);480 response.end(errorResponse);481 }482 });483}484/**485 *486 */487function handleRequestAsViewStream(request, response) {488 var requestView = request.url.split('/');489 console.log(requestView[2]);490 // serve request as a view491 handleRequestAsFileStream({492 url : '/view/' + requestView[2]493 }, response);494}495/**496 * handle all requests formed as /post and echos / relays it back to the client497 */498function handleRequestAsEchoPost(request, response) {499 if(request.method != 'POST') {500 setDefaultHeaders(SERVER_HEAD_ERROR, request, response);501 response.end(SERVER_RES_ERROR);502 }503 var postData = '';504 request.on('data', function(chunk) {505 postData += chunk;506 });507 request.on('end', function() {508 setDefaultHeaders(SERVER_HEAD_OK, request, response);509 response.end(postData);510 });511}512/**513 * handle all initial application requests, assign routes, etc.514 */515function mainRequestHandler(request, response) {516 // assign global definition for current request being handled517 currentRequest = requestRouter(request, response);518 if(typeof currentRequest == 'function') {519 currentRequest(request, response);520 } else if(currentRequest.match(/^\/test(\/)?$/gi)) {521 setDefaultHeaders(SERVER_HEAD_OK, request, response);522 response.end(SERVER_RES_OK);523 } else if(currentRequest.match(/^\/api\/post\/(.*)/gi)) {524 } else if(currentRequest.match(/^\/api\/post\/(.*)/gi)) {525 handleRequestAsAPIPOSTCall(request, response);526 } else if(currentRequest.match(/^\/api\/(.*)/gi)) {527 handleRequestAsAPICall(request, response);528 } else if(currentRequest.match(/^\/get\/(.*)/gi)) {529 handleRequestAsGETEndpoint(request, response);530 } else if(currentRequest.match(/^\/view\/(.*)/gi)) {531 handleRequestAsViewStream(request, response);532 } else {533 handleRequestAsFileStream(request, response);534 }535}...
rest_angular.js
Source:rest_angular.js
...6angular.module('rsc.common.service.rest', ['restangular'])7 .factory('AccountRestAngularNoToken', function (Restangular, ENV) {8 return Restangular.withConfig(function (RestangularConfigurer) {9 if (ENV.encode) {10 RestangularConfigurer.setDefaultHeaders({11 'x-access-token': {},12 server_type: 'user'13 });14 } else {15 RestangularConfigurer.setDefaultHeaders({16 'x-access-token': {}17 });18 RestangularConfigurer.setBaseUrl(ENV.api.account);19 }20 })21 })22 .factory('AccountRestAngular', function (Restangular, ENV, GetToken) {23 return Restangular.withConfig(function (RestangularConfigurer) {24 if (ENV.encode) {25 RestangularConfigurer.setDefaultHeaders({26 'x-access-token': GetToken.getToken(),27 server_type: 'user'28 });29 } else {30 RestangularConfigurer.setDefaultHeaders({31 'x-access-token': GetToken.getToken()32 });33 RestangularConfigurer.setBaseUrl(ENV.api.account);34 }35 })36 })37 .factory('PassRestAngular', function (Restangular, ENV, GetToken) {38 return Restangular.withConfig(function (RestangularConfigurer) {39 if (ENV.encode) {40 RestangularConfigurer.setDefaultHeaders({41 'x-access-token': GetToken.getToken(),42 server_type: 'traffic'43 });44 } else {45 RestangularConfigurer.setDefaultHeaders({46 'x-access-token': GetToken.getToken()47 });48 RestangularConfigurer.setBaseUrl(ENV.api.pass);49 }50 })51 })52 .factory('PassPayAngular', function (Restangular, ENV, GetToken) {53 return Restangular.withConfig(function (RestangularConfigurer) {54 if (ENV.encode) {55 RestangularConfigurer.setDefaultHeaders({56 "Content-Type": undefined57 });58 RestangularConfigurer.setDefaultHeaders({59 'x-access-token': GetToken.getToken(),60 server_type: 'traffic'61 });62 } else {63 RestangularConfigurer.setDefaultHeaders({64 "Content-Type": undefined65 });66 RestangularConfigurer.setDefaultHeaders({67 'x-access-token': GetToken.getToken()68 });69 RestangularConfigurer.setBaseUrl(ENV.api.pass);70 }71 })72 })73 .factory('StoreRestAngular', function (Restangular, ENV, GetToken) {74 return Restangular.withConfig(function (RestangularConfigurer) {75 if (ENV.encode) {76 RestangularConfigurer.setDefaultHeaders({77 'x-access-token': GetToken.getToken(),78 server_type: 'user'79 });80 } else {81 RestangularConfigurer.setDefaultHeaders({82 'x-access-token': GetToken.getToken()83 });84 RestangularConfigurer.setBaseUrl(ENV.api.account);85 }86 });87 })88 .factory('CreditRestAngular', function (Restangular, ENV, GetToken) {89 return Restangular.withConfig(function (RestangularConfigurer) {90 if (ENV.encode) {91 RestangularConfigurer.setDefaultHeaders({92 'x-access-token': GetToken.getToken(),93 server_type: 'finance'94 });95 } else {96 RestangularConfigurer.setDefaultHeaders({97 'x-access-token': GetToken.getToken()98 });99 RestangularConfigurer.setBaseUrl(ENV.api.credit);100 }101 });102 })103 .factory('TradeRestAngular', function (Restangular, ENV, GetToken) {104 return Restangular.withConfig(function (RestangularConfigurer) {105 if (ENV.encode) {106 RestangularConfigurer.setDefaultHeaders({107 'x-access-token': GetToken.getToken(),108 server_type: 'trade'109 });110 } else {111 RestangularConfigurer.setDefaultHeaders({112 'x-access-token': GetToken.getToken()113 });114 RestangularConfigurer.setBaseUrl(ENV.api.trade);115 }116 });117 })118 .factory('LogServiceAngular', function (Restangular, ENV, GetToken) {119 return Restangular.withConfig(function (RestangularConfigurer) {120 if (ENV.encode) {121 RestangularConfigurer.setDefaultHeaders({122 'x-access-token': GetToken.getToken(),123 server_type: 'log'124 });125 } else {126 RestangularConfigurer.setDefaultHeaders({127 'x-access-token': GetToken.getToken()128 });129 RestangularConfigurer.setBaseUrl(ENV.api.log);130 }131 });132 })133 .factory('MsgServiceAngular', function (Restangular, ENV, GetToken) {134 return Restangular.withConfig(function (RestangularConfigurer) {135 if (ENV.encode) {136 RestangularConfigurer.setDefaultHeaders({137 'x-access-token': GetToken.getToken(),138 server_type: 'msg'139 });140 } else {141 RestangularConfigurer.setDefaultHeaders({142 'x-access-token': GetToken.getToken()143 });144 RestangularConfigurer.setBaseUrl(ENV.api.msg);145 }146 });147 })148 .factory('AdminServiceAngular', function (Restangular, ENV, GetToken) {149 return Restangular.withConfig(function (RestangularConfigurer) {150 if (ENV.encode) {151 RestangularConfigurer.setDefaultHeaders({152 'x-access-token': GetToken.getToken(),153 server_type: 'admin'154 });155 } else {156 RestangularConfigurer.setDefaultHeaders({157 'x-access-token': GetToken.getToken()158 });159 RestangularConfigurer.setBaseUrl(ENV.api.admin);160 }161 });162 })163 .factory('StatistServiceAngular', function (Restangular, ENV, GetToken) {164 return Restangular.withConfig(function (RestangularConfigurer) {165 if (ENV.encode) {166 RestangularConfigurer.setDefaultHeaders({167 'x-access-token': GetToken.getToken(),168 server_type: 'statist'169 });170 } else {171 RestangularConfigurer.setDefaultHeaders({172 'x-access-token': GetToken.getToken()173 });174 RestangularConfigurer.setBaseUrl(ENV.api.statist);175 }176 });177 })178 .factory('ContactAngular', function (Restangular, ENV, GetToken) {179 return Restangular.withConfig(function (RestangularConfigurer) {180 if (ENV.encode) {181 RestangularConfigurer.setDefaultHeaders({182 'x-access-token': GetToken,183 server_type: 'contact'184 });185 } else {186 RestangularConfigurer.setDefaultHeaders({187 'x-access-token': GetToken188 });189 RestangularConfigurer.setBaseUrl(ENV.api.contact);190 }191 });192 })193 .factory('DynamicAngular', function (Restangular, ENV, GetToken) {194 return Restangular.withConfig(function (RestangularConfigurer) {195 if (ENV.encode) {196 RestangularConfigurer.setDefaultHeaders({197 'x-access-token': GetToken,198 server_type: 'dynamic'199 });200 } else {201 RestangularConfigurer.setDefaultHeaders({202 'x-access-token': GetToken203 });204 RestangularConfigurer.setBaseUrl(ENV.api.dynamic);205 }206 });207 })208 .factory('GetToken', function (AuthenticationService) {209 return {210 getToken: function () {211 var token;212 var user = AuthenticationService.getUserInfo();213 //var user = window.sessionStorage.setItem('userInfo', window.JSON.stringify(data));214 if (user) {215 token = user.token;216 } else {217 token = '';218 }219 return token;220 }221 }222 })223 .factory('AuthenticationService', ['Storage', '$log', '$location', '$q', function (Storage, $log, $location, $q) {224 var userInfo;225 var companyInfo;226 function getUserInfo() {227 if (Storage.get('userInfo')) {228 userInfo = Storage.get('userInfo');229 return userInfo;230 } else {231 //$log.warn("no login");232 // $location.path('/tab/login')233 // window.location.href = 'http://'+$location.$$host+':'+ $location.$$port + '#/tab/login'234 return null;235 }236 }237 function getCompanyInfo() {238 if (Storage.get('userInfo').company) {239 companyInfo = Storage.get('userInfo').company;240 return companyInfo;241 } else {242 return null;243 }244 }245 return {246 getUserInfo: getUserInfo,247 getCompanyInfo: getCompanyInfo,248 checkToken: function () {249 userInfo = getUserInfo();250 if (userInfo) {251 return $q.when(userInfo);252 } else {253 return $q.reject({254 authenticated: false255 })256 }257 }258 };259 }])260 .factory('NewTradeRestAngular', function (Restangular, ENV, GetToken) {261 return Restangular.withConfig(function (RestangularConfigurer) {262 if (ENV.encode) {263 RestangularConfigurer.setDefaultHeaders({264 'x-access-token': GetToken.getToken(),265 server_type: 'user'266 });267 } else {268 RestangularConfigurer.setDefaultHeaders({269 'x-access-token': GetToken.getToken()270 });271 RestangularConfigurer.setBaseUrl(ENV.api.newtrade);272 }273 })274 })275 .factory('MsgServiceAngular', function (Restangular, ENV, GetToken) {276 return Restangular.withConfig(function (RestangularConfigurer) {277 if (ENV.encode) {278 RestangularConfigurer.setDefaultHeaders({279 'x-access-token': GetToken.getToken(),280 server_type: 'msg'281 });282 } else {283 RestangularConfigurer.setDefaultHeaders({284 'x-access-token': GetToken.getToken()285 });286 RestangularConfigurer.setBaseUrl(ENV.api.msg);287 }288 });289 })290 .factory('WebIMAngular', function (Restangular, ENV, GetToken) {291 return Restangular.withConfig(function (RestangularConfigurer) {292 if (ENV.encode) {293 RestangularConfigurer.setDefaultHeaders({294 'x-access-token': GetToken.getToken(),295 server_type: 'webim'296 });297 } else {298 RestangularConfigurer.setDefaultHeaders({299 'x-access-token': GetToken.getToken()300 });301 RestangularConfigurer.setBaseUrl(ENV.api.webim);302 }303 });304 })305 .factory('MapServiceAngular', function (Restangular, ENV, GetToken) {306 return Restangular.withConfig(function (RestangularConfigurer) {307 if (ENV.encode) {308 RestangularConfigurer.setDefaultHeaders({309 'x-access-token': GetToken.getToken(),310 server_type: 'map'311 });312 } else {313 314 RestangularConfigurer.setDefaultHeaders({315 'x-access-token': GetToken.getToken()316 });317 RestangularConfigurer.setBaseUrl(ENV.api.map);318 }319 });320 })321 //家æ¿æå¡è¶
å¸è¯·æ±æ¥å£322 .factory('XnRestAngular', function (Restangular, ENV, GetToken) {323 return Restangular.withConfig(function (RestangularConfigurer) {324 if (ENV.encode) {325 326 RestangularConfigurer.setDefaultHeaders({327 'x-access-token': GetToken.getToken(),328 'Content-Type': 'application/x-www-form-urlencoded'329 });330 } else {331 332 RestangularConfigurer.setDefaultHeaders({333 'x-access-token': GetToken.getToken(),334 'Content-Type': 'application/x-www-form-urlencoded'335 });336 RestangularConfigurer.setDefaultHttpFields({337 transformRequest: function(data) {338 var str=[];339 for(var p in data){340 str.push(encodeURIComponent(p)+"="+encodeURIComponent(data[p]));341 }342 return str.join("&");343 }344 }); 345 RestangularConfigurer.setBaseUrl(ENV.api.xnHome);346 }...
restangular.js
Source:restangular.js
...6angular.module('rsc.service.rest', ['restangular'])7 .factory('AccountRestAngularNoToken', function (Restangular, ENV) {8 return Restangular.withConfig(function (RestangularConfigurer) {9 if (ENV.encode) {10 RestangularConfigurer.setDefaultHeaders({11 'x-access-token': {},12 server_type: 'user'13 });14 } else {15 RestangularConfigurer.setDefaultHeaders({16 'x-access-token': {}17 });18 RestangularConfigurer.setBaseUrl(ENV.api.account);19 }20 })21 })22 // .factory('AccountRestAngular', function (Restangular, ENV, GetToken) {23 // return Restangular.withConfig(function (RestangularConfigurer) {24 // if (ENV.encode) {25 // RestangularConfigurer.setDefaultHeaders({26 // 'x-access-token': GetToken.getToken(),27 // server_type: 'user'28 // });29 // } else {30 // RestangularConfigurer.setDefaultHeaders({31 // 'x-access-token': GetToken.getToken()32 // });33 // RestangularConfigurer.setBaseUrl(ENV.api.account);34 // }35 // })36 // })37 .factory('PassRestAngular', function (Restangular, ENV, GetToken) {38 return Restangular.withConfig(function (RestangularConfigurer) {39 if (ENV.encode) {40 RestangularConfigurer.setDefaultHeaders({41 'x-access-token': GetToken.getToken(),42 server_type: 'traffic'43 });44 } else {45 RestangularConfigurer.setDefaultHeaders({46 'x-access-token': GetToken.getToken()47 });48 RestangularConfigurer.setBaseUrl(ENV.api.pass);49 }50 })51 })52 .factory('PassPayAngular', function (Restangular, ENV, GetToken) {53 return Restangular.withConfig(function (RestangularConfigurer) {54 if (ENV.encode) {55 RestangularConfigurer.setDefaultHeaders({56 "Content-Type": undefined57 });58 RestangularConfigurer.setDefaultHeaders({59 'x-access-token': GetToken.getToken(),60 server_type: 'traffic'61 });62 } else {63 RestangularConfigurer.setDefaultHeaders({64 "Content-Type": undefined65 });66 RestangularConfigurer.setDefaultHeaders({67 'x-access-token': GetToken.getToken()68 });69 RestangularConfigurer.setBaseUrl(ENV.api.pass);70 }71 })72 })73 .factory('StoreRestAngular', function (Restangular, ENV, GetToken) {74 return Restangular.withConfig(function (RestangularConfigurer) {75 if (ENV.encode) {76 RestangularConfigurer.setDefaultHeaders({77 'x-access-token': GetToken.getToken(),78 server_type: 'user'79 });80 } else {81 RestangularConfigurer.setDefaultHeaders({82 'x-access-token': GetToken.getToken()83 });84 RestangularConfigurer.setBaseUrl(ENV.api.account);85 }86 });87 })88 .factory('CreditRestAngular', function (Restangular, ENV, GetToken) {89 return Restangular.withConfig(function (RestangularConfigurer) {90 if (ENV.encode) {91 RestangularConfigurer.setDefaultHeaders({92 'x-access-token': GetToken.getToken(),93 server_type: 'finance'94 });95 } else {96 RestangularConfigurer.setDefaultHeaders({97 'x-access-token': GetToken.getToken()98 });99 RestangularConfigurer.setBaseUrl(ENV.api.credit);100 }101 });102 })103 .factory('TradeRestAngular', function (Restangular, ENV, GetToken) {104 return Restangular.withConfig(function (RestangularConfigurer) {105 if (ENV.encode) {106 RestangularConfigurer.setDefaultHeaders({107 'x-access-token': GetToken.getToken(),108 server_type: 'trade'109 });110 } else {111 RestangularConfigurer.setDefaultHeaders({112 'x-access-token': GetToken.getToken()113 });114 RestangularConfigurer.setBaseUrl(ENV.api.trade);115 }116 });117 })118 .factory('LogServiceAngular', function (Restangular, ENV, GetToken) {119 return Restangular.withConfig(function (RestangularConfigurer) {120 if (ENV.encode) {121 RestangularConfigurer.setDefaultHeaders({122 'x-access-token': GetToken.getToken(),123 server_type: 'log'124 });125 } else {126 RestangularConfigurer.setDefaultHeaders({127 'x-access-token': GetToken.getToken()128 });129 RestangularConfigurer.setBaseUrl(ENV.api.log);130 }131 });132 })133 .factory('AdminServiceAngular', function (Restangular, ENV, GetToken) {134 return Restangular.withConfig(function (RestangularConfigurer) {135 if (ENV.encode) {136 RestangularConfigurer.setDefaultHeaders({137 'x-access-token': GetToken.getToken(),138 server_type: 'admin'139 });140 } else {141 RestangularConfigurer.setDefaultHeaders({142 'x-access-token': GetToken.getToken()143 });144 RestangularConfigurer.setBaseUrl(ENV.api.admin);145 }146 });147 })148 .factory('StatistServiceAngular', function (Restangular, ENV, GetToken) {149 return Restangular.withConfig(function (RestangularConfigurer) {150 if (ENV.encode) {151 RestangularConfigurer.setDefaultHeaders({152 'x-access-token': GetToken.getToken(),153 server_type: 'statist'154 });155 } else {156 RestangularConfigurer.setDefaultHeaders({157 'x-access-token': GetToken.getToken()158 });159 RestangularConfigurer.setBaseUrl(ENV.api.statist);160 }161 });162 })163 .factory('ContactAngular', function (Restangular, ENV, GetToken) {164 return Restangular.withConfig(function (RestangularConfigurer) {165 if (ENV.encode) {166 RestangularConfigurer.setDefaultHeaders({167 'x-access-token': GetToken,168 server_type: 'contact'169 });170 } else {171 RestangularConfigurer.setDefaultHeaders({172 'x-access-token': GetToken173 });174 RestangularConfigurer.setBaseUrl(ENV.api.contact);175 }176 });177 })178 .factory('DynamicAngular', function (Restangular, ENV, GetToken) {179 return Restangular.withConfig(function (RestangularConfigurer) {180 if (ENV.encode) {181 RestangularConfigurer.setDefaultHeaders({182 'x-access-token': GetToken,183 server_type: 'dynamic'184 });185 } else {186 RestangularConfigurer.setDefaultHeaders({187 'x-access-token': GetToken188 });189 RestangularConfigurer.setBaseUrl(ENV.api.dynamic);190 }191 });192 })193 .factory('GetToken', function (AuthenticationService) {194 return {195 getToken: function () {196 var token;197 var user = AuthenticationService.getUserInfo();198 //var user = window.sessionStorage.setItem('userInfo', window.JSON.stringify(data));199 if (user) {200 token = user.token;201 } else {202 token = '';203 }204 return token;205 }206 }207 })208 .factory('AuthenticationService', ['Storage', '$log', '$location', '$q', function (Storage, $log, $location, $q) {209 var userInfo;210 var companyInfo;211 function getUserInfo() {212 if (Storage.get('userInfo')) {213 userInfo = Storage.get('userInfo');214 return userInfo;215 } else {216 //$log.warn("no login");217 // $location.path('/tab/login')218 // window.location.href = 'http://'+$location.$$host+':'+ $location.$$port + '#/tab/login'219 return null;220 }221 }222 function getCompanyInfo() {223 if (Storage.get('userInfo').company) {224 companyInfo = Storage.get('userInfo').company;225 return companyInfo;226 } else {227 return null;228 }229 }230 return {231 getUserInfo: getUserInfo,232 getCompanyInfo: getCompanyInfo,233 checkToken: function () {234 userInfo = getUserInfo();235 if (userInfo) {236 return $q.when(userInfo);237 } else {238 return $q.reject({239 authenticated: false240 })241 }242 }243 };244 }])245 .factory('NewTradeRestAngular', function (Restangular, ENV, GetToken) {246 return Restangular.withConfig(function (RestangularConfigurer) {247 if (ENV.encode) {248 RestangularConfigurer.setDefaultHeaders({249 'x-access-token': GetToken.getToken(),250 server_type: 'user'251 });252 } else {253 RestangularConfigurer.setDefaultHeaders({254 'x-access-token': GetToken.getToken()255 });256 RestangularConfigurer.setBaseUrl(ENV.api.newtrade);257 }258 })...
http-configurer.service.spec.js
Source:http-configurer.service.spec.js
1'use strict';2/* global chai, sinon: false */3var { expect } = chai;4describe('The esn.http httpConfigurer service', function() {5 var httpConfigurer;6 beforeEach(angular.mock.module('esn.http'));7 beforeEach(angular.mock.inject(function(_$httpBackend_, _httpConfigurer_) {8 httpConfigurer = _httpConfigurer_;9 }));10 describe('manageRestangular fn', function() {11 it('should prepend the current baseUrl', function() {12 const raInstance = {13 setBaseUrl: sinon.spy(),14 setDefaultHeaders: sinon.spy()15 };16 httpConfigurer.setBaseUrl('/test1');17 httpConfigurer.manageRestangular(raInstance, '/mod1/api');18 expect(raInstance.setBaseUrl).to.have.been.calledWith('/test1/mod1/api');19 });20 it('should update the baseUrl when setBaseUrl is called', function() {21 const raInstance = {22 setBaseUrl: sinon.spy(),23 setDefaultHeaders: sinon.spy()24 };25 httpConfigurer.setBaseUrl('/test1');26 httpConfigurer.manageRestangular(raInstance, '/mod1/api');27 raInstance.setBaseUrl = sinon.spy();28 httpConfigurer.setBaseUrl('/test2');29 expect(raInstance.setBaseUrl).to.have.been.calledWith('/test2/mod1/api');30 });31 it('should set the headers to restangular instances', function() {32 const headers = { Authorization: 'bearer 1234' };33 const raInstance = {34 setBaseUrl: sinon.spy(),35 setDefaultHeaders: sinon.spy()36 };37 httpConfigurer.setBaseUrl('/test1');38 httpConfigurer.setHeaders(headers);39 httpConfigurer.manageRestangular(raInstance, '/mod1/api');40 expect(raInstance.setDefaultHeaders).to.have.been.calledWith(headers);41 });42 it('should update the headers when setHeaders is called', function() {43 const headers = { Authorization: 'bearer 1234' };44 const raInstance = {45 setBaseUrl: sinon.spy(),46 setDefaultHeaders: sinon.spy()47 };48 httpConfigurer.setBaseUrl('/test1');49 httpConfigurer.setHeaders({ foo: 'bar' });50 httpConfigurer.manageRestangular(raInstance, '/mod1/api');51 raInstance.setDefaultHeaders = sinon.spy();52 httpConfigurer.setHeaders(headers);53 expect(raInstance.setDefaultHeaders).to.have.been.calledWith(headers);54 });55 });56 describe('getUrl()', function() {57 it('should return the baseUrl set by setBaseUrl', function() {58 var theBaseUrl = '/someUrl';59 httpConfigurer.setBaseUrl(theBaseUrl);60 expect(httpConfigurer.getUrl('')).to.equal(theBaseUrl);61 });62 it('should prepend the given URL to the baseUrl', function() {63 var theBaseUrl = '/someUrl';64 var theSpecificUrl = '/someApi';65 httpConfigurer.setBaseUrl(theBaseUrl);66 expect(httpConfigurer.getUrl(theSpecificUrl)).to.equal(theBaseUrl + theSpecificUrl);67 });68 it('should deal with undefined specific URI', function() {69 var theBaseUrl = '/someUrl';70 httpConfigurer.setBaseUrl(theBaseUrl);71 expect(httpConfigurer.getUrl()).to.equal(theBaseUrl);72 });73 });74 describe('setBaseUrl()', function() {75 it('should trim the last trailing slash', function() {76 var theBaseUrl = '/someUrl';77 httpConfigurer.setBaseUrl(theBaseUrl + '/');78 expect(httpConfigurer.getUrl()).to.equal(theBaseUrl);79 });80 });81 describe('getHeaders()', function() {82 it('should send back an empty object when no specific header is set', function() {83 expect(httpConfigurer.getHeaders()).to.deep.equal({});84 });85 it('should send back the specific headers', function() {86 const headers = { Authorization: 'Bearer 1234' };87 httpConfigurer.setHeaders(headers);88 expect(httpConfigurer.getHeaders()).to.deep.equal(headers);89 });90 });...
request.js
Source:request.js
...26 .post(resolve(apiUrl, path))27 .send(rest)28 .set('Content-Type', 'application/json')29 .set('Accept', 'application/json')30 .set(setDefaultHeaders())31 .use(unauthorizedRedirect);3233export const put = (path, ...rest) =>34 req35 .put(resolve(apiUrl, path), ...rest)36 .set('Content-Type', 'application/json')37 .set('Accept', 'application/json')38 .set(setDefaultHeaders())39 .use(unauthorizedRedirect);4041export const patch = (path, ...rest) =>42 req43 .patch(resolve(apiUrl, path), ...rest)44 .set('Content-Type', 'application/json')45 .set('Accept', 'application/json')46 .set(setDefaultHeaders())47 .use(unauthorizedRedirect);4849export const del = (path, ...rest) =>50 req51 .del(resolve(apiUrl, path), ...rest)52 .set('Content-Type', 'application/json')53 .set('Accept', 'application/json')54 .set(setDefaultHeaders())55 .use(unauthorizedRedirect);5657export const get = async (path, ...rest) =>58 req59 .get(resolve(apiUrl, path), ...rest)60 .set('Content-Type', 'application/json')61 .set('Accept', 'application/json')62 .set(setDefaultHeaders())63 .use(unauthorizedRedirect);6465export const head = (path, ...rest) =>66 req67 .head(resolve(apiUrl, path), ...rest)68 .set('Content-Type', 'application/json')69 .set('Accept', 'application/json')70 .set(setDefaultHeaders())
...
http.js
Source:http.js
...11 'Accept': 'application/json'12 }13 }14 15 setDefaultHeaders(headers={}) {16 headers = {17 ...this.default_headers,18 ...headers19 }20 return new Headers(headers)21 }22 checkStatus(response) {23 // TODO catch 401 and redirect to login24 /*if (response.status == 401) {25 console.log(401)26 }*/27 if (response.status >= 200 && response.status < 300) {28 return response29 } else {30 let error = new Error(response.status)31 error.response = response32 throw error33 }34 }35 get(url, headers={}) {36 return fetch(url,37 {38 method: "GET",39 credentials: 'same-origin',40 headers: this.setDefaultHeaders(headers)41 })42 .then(this.checkStatus)43 .then(response => response.json())44 }45 post(url, headers={}, body) {46 return fetch(url,47 {48 method: "POST",49 credentials: 'same-origin',50 headers: this.setDefaultHeaders(headers),51 body: body52 })53 .then(this.checkStatus)54 .then(response => response.json())55 }56 put(url, headers={}, body) {57 return fetch(url,58 {59 method: "PUT",60 credentials: 'same-origin',61 headers: this.setDefaultHeaders(headers),62 body: body63 })64 .then(this.checkStatus)65 .then(response => response.json())66 }67 patch(url, headers={}, body) {68 return fetch(url,69 {70 method: "PATCH",71 credentials: 'same-origin',72 headers: this.setDefaultHeaders(headers),73 body: body74 })75 .then(this.checkStatus)76 .then(response => response.json())77 }78 delete(url, headers={}) {79 return fetch(url,80 {81 method: "DELETE",82 credentials: 'same-origin',83 headers: this.setDefaultHeaders(headers)84 })85 .then(this.checkStatus)86 }87}...
fetchTimeout.spec.js
Source:fetchTimeout.spec.js
2import { setDefaultHeaders } from './fetchTimeout.js'3describe('ui/hooks', function () {4 describe('setDefaultHeaders', function () {5 it('shall not add default header', function () {6 assert.deepStrictEqual(setDefaultHeaders(), {})7 })8 it('shall not add default header for GET', function () {9 assert.deepStrictEqual(setDefaultHeaders({ method: 'GET' }), { method: 'GET' })10 })11 it('shall add Content-Type for POST', function () {12 assert.deepStrictEqual(setDefaultHeaders({ method: 'POST' }), {13 method: 'POST',14 headers: { 'Content-Type': 'application/json; charset=utf-8' }15 })16 })17 it('shall add Content-Type for PUT', function () {18 assert.deepStrictEqual(setDefaultHeaders({ method: 'PUT', headers: { 'X-Custom': 'Custom header' } }), {19 method: 'PUT',20 headers: { 'Content-Type': 'application/json; charset=utf-8', 'X-Custom': 'Custom header' }21 })22 })23 it('shall add Content-Type for PATCH', function () {24 assert.deepStrictEqual(setDefaultHeaders({ method: 'PATCH', headers: { 'X-Custom': 'Custom header' } }), {25 method: 'PATCH',26 headers: { 'Content-Type': 'application/json; charset=utf-8', 'X-Custom': 'Custom header' }27 })28 })29 })...
restangular.config.js
Source:restangular.config.js
...9 .config(configuration);10 /* @ngInject */11 function configuration(RestangularProvider){12 // var defaultHeaders = {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'};13 // RestangularProvider.setDefaultHeaders(defaultHeaders);14 // RestangularProvider.setDefaultHeaders({15 // 'Content-Type': 'application/json',16 // 'X-Requested-With': 'XMLHttpRequest'17 // });18 // RestangularProvider.setDefaultHeaders({'Access-Control-Allow-Origin':'*'});19 // RestangularProvider.setDefaultHeaders({'Access-Control-Allow-core':'*'});20 RestangularProvider.setDefaultHeaders({21 'Content-Type': 'application/json',22 'X-Requested-With': 'XMLHttpRequest',23 'Access-Control-Allow-Origin':'*',24 'Access-Control-Allow-core':'*',25 'Access-Control-Allow-Headers':'Accept, X-Requested-With',26 'Access-Control-Allow-Credentials':'true'27 });28 RestangularProvider.setBaseUrl('/api');29 }...
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1Cypress.Commands.add('setDefaultHeaders', (headers) => {2 Cypress.on('window:before:load', (win) => {3 win.fetch = null;4 });5 cy.on('window:before:load', (win) => {6 win.fetch = null;7 });8 cy.server({9 response: {},10 });11});12Cypress.Commands.add('setDefaultHeaders', (headers) => {13 Cypress.on('window:before:load', (win) => {14 win.fetch = null;15 });16 cy.on('window:before:load', (win) => {17 win.fetch = null;18 });19 cy.server({20 response: {},21 });22});23Cypress.Commands.add('setDefaultHeaders', (headers) => {24 Cypress.on('window:before:load', (win) => {25 win.fetch = null;26 });27 cy.on('window:before:load', (win) => {28 win.fetch = null;29 });30 cy.server({31 response: {},32 });33});34Cypress.Commands.add('setDefaultHeaders', (headers) => {35 Cypress.on('window:before:load', (win) => {36 win.fetch = null;37 });38 cy.on('window:before:load', (win) => {39 win.fetch = null;40 });41 cy.server({42 response: {},43 });44});45Cypress.Commands.add('setDefaultHeaders', (headers) => {46 Cypress.on('window:before:load', (win) => {47 win.fetch = null;48 });49 cy.on('window:before:load', (win) => {50 win.fetch = null;51 });52 cy.server({53 response: {},54 });55});56Cypress.Commands.add('setDefaultHeaders', (headers) => {57 Cypress.on('window:before:load', (win) => {58 win.fetch = null;
Using AI Code Generation
1Cypress.Commands.add('setDefaultHeaders', (headers) => {2 cy.on('window:before:load', (win) => {3 win.fetch = (resource, init) => {4 return fetch(resource, init)5 }6 })7})8Cypress.Commands.add('setDefaultHeaders', (headers) => {9 cy.on('window:before:load', (win) => {10 win.fetch = (resource, init) => {11 return fetch(resource, init)12 }13 })14})15Cypress.Commands.add('setDefaultHeaders', (headers) => {16 cy.on('window:before:load', (win) => {17 win.fetch = (resource, init) => {18 return fetch(resource, init)19 }20 })21})22Cypress.Commands.add('setDefaultHeaders', (headers) => {23 cy.on('window:before:load', (win) => {24 win.fetch = (resource, init) => {25 return fetch(resource, init)26 }27 })28})29Cypress.Commands.add('setDefaultHeaders', (headers) => {30 cy.on('window:before:load', (win) => {31 win.fetch = (resource, init) => {32 return fetch(resource, init)33 }34 })35})36Cypress.Commands.add('setDefaultHeaders', (headers) => {37 cy.on('window:before:load', (win) => {38 win.fetch = (resource, init) => {39 return fetch(resource, init)40 }41 })42})43Cypress.Commands.add('setDefaultHeaders', (headers) => {44 cy.on('window:before:load', (win) => {45 win.fetch = (resource, init) => {46 return fetch(resource, init)47 }48 })49})50Cypress.Commands.add('setDefaultHeaders', (headers) => {51 cy.on('window:before:load', (win) => {
Using AI Code Generation
1describe('Cypress Demo', function() {2 it('Test case to set headers', function() {3 cy.request({4 headers: {5 }6 }).then(function(response) {7 expect(response.status).to.eq(200)8 })9 })10})11Cypress.config('defaultCommandTimeout', 10000)12Cypress.config('headers', {13})14describe('Cypress Demo', function() {15 it('Test case to set headers', function() {16 cy.request({17 }).then(function(response) {18 expect(response.status).to.eq(200)19 })20 })21})22Cypress.config('defaultCommandTimeout', 10000)23Cypress.config('headers', {24})25describe('Cypress Demo', function() {26 it('Test case to set headers', function() {27 cy.request({28 }).then(function(response) {29 expect(response.status).to.eq(200)30 })31 })32})
Using AI Code Generation
1describe("Test", () => {2 Cypress.on("window:before:load", (win) => {3 win.fetch = null;4 });5 beforeEach(() => {6 cy.server();7 cy.setDefaultHeaders({8 });9 });10 it("test", () => {11 cy.route({12 }).as("test");13 cy.wait("@test");14 cy.get("h1").should("contain", "test");15 });16});17Cypress.on("window:before:load", (win) => {18 win.fetch = null;19});20Cypress.setDefaultHeaders = (headers) => {21 Cypress.on("window:before:load", (win) => {22 const originalOpen = win.XMLHttpRequest.prototype.open;23 win.XMLHttpRequest.prototype.open = function (method, url) {24 originalOpen.apply(this, [method, url]);25 Object.keys(headers).forEach((key) => {26 this.setRequestHeader(key, headers[key]);27 });28 };29 });30};31Cypress.Commands.add("setDefaultHeaders", (headers) => {32 Cypress.on("window:before:load", (win) => {33 const originalOpen = win.XMLHttpRequest.prototype.open;34 win.XMLHttpRequest.prototype.open = function (method, url) {35 originalOpen.apply(this, [method, url]);36 Object.keys(headers).forEach((key) => {37 this.setRequestHeader(key, headers[key]);38 });39 };40 });41});42Your name to display (optional):43Your name to display (optional):
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.
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.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!