Best JavaScript code snippet using apimocker
HttpRequest.js
Source:HttpRequest.js
1import axios from 'axios'2import { Toast } from 'mint-ui';3import tool from '@common/libs/tool'4export class HttpRequest {5 //mark:æ°å¢6 // dependentPro 请æ±ä¾èµç Promise7 set dependentPro (newValue) {8 if (this._dependentResolve) {9 this._dependentResolve(newValue);10 }11 this._dependentPro = newValue ;12 }13 get dependentPro () {14 if (!this._dependentPro) {15 this._dependentPro = new Promise((resolve, reject)=> {16 this._dependentResolve = resolve ;17 });18 }19 return this._dependentPro ;20 }21 //mark:ç»æ22 /**23 * å建HTTP请æ±å¯¹è±¡24 * @param httpConfig : Object HTTPçé
置对象ï¼25 *26 * httpConfig ä¸å¯é
ç½®çå段å¦ä¸ï¼27 *28 * httpConfig.baseURL : string åºURL29 * httpConfig.method : string é»è®¤ç请æ±æ¹å¼30 * httpConfig.reqTransforms : [(ReqOptions)=>ReqOptions] 转æ¢è¯·æ±é项ç转æ¢å½æ°æ°ç»ï¼ç¨äºå¯¹reqOptionsè¿è¡è½¬æ¢ï¼ä¹å¯ä»¥å¨å½æ°éç»æ°æ®æ·»å ä¸äºå
Œ
±çåæ°31 * httpConfig.resTransforms : [(Response,ReqOptions)=>Response] 转æ¢ååºç转æ¢å½æ°æ°ç»ï¼ç¨äºå¯¹ response è¿è¡è½¬æ¢ï¼32 * httpConfig.headers : Object é»è®¤ç请æ±å¤´å¯¹è±¡33 * httpConfig.mainData : boolean å½è¯·æ±æåæ¶ï¼æ¯å¦è¿åç»è¿ mainDataGet å¤çè¿çæ°æ®ï¼34 * httpConfig.mainDataGet : function å¦æ mainData 设置为 trueï¼å½è¯·æ±æåæ¶ï¼ä¼è¿å被 mainDataGet å¤çè¿çæ°æ®ï¼35 * httpConfig.successPrompt : boolean æ¯å¦å¯ç¨å
¨å±çæåæ示ï¼36 * httpConfig.failPrompt : boolean æ¯å¯ç¨ç¨å
¨å±ç失败æ示;37 * httpConfig.showLoading : boolean æ¯å¦å¯ç¨å è½½ç¶ææ示ï¼é»è®¤å¼ä¸º true38 * httpConfig.loadText : string å è½½çæ示ææ¬39 * @returns AxiosPromise 请æ±ç AxiosPromise 对象40 *41 *42 * //mark: æ°å 43 * dependent : boolean 设置请æ±æ¯å¦ä¾èµ dependentPro44 * dependentPro : Promise 请æ±çä¾èµé¡¹ï¼å½è¯·æ±æä¾èµæ¶ï¼è¯·æ±ä¼ çå° dependentPro 解å³ä¹å触å45 * dependResultHandle : (result,reqOptions)=> HandleResult : ReqOptions || boolean || null || undefined ä¾èµç»æå¤çå¨ï¼å½è¯·æ±æä¾èµæ¶ï¼å¨ ä¾èµè§£å³ä¹å 请æ±è§£å³ä¹å è°ç¨è¯¥å¤çå¨ï¼46 *47 * 注æï¼48 * - å½ HandleResult 为 false æ¶ï¼ä¼åæ¶è¯·æ±ï¼49 * - å½ HandleResult 为 éåå¼æ¶ï¼ ä¼ä½¿ç¨ HandleResult è¿è¡è¯·æ±ï¼50 * - å½ HandleResult 为 é¤ false ä¹å¤çåå¼æ¶ï¼ä¼ä½¿ç¨ åæ¥ç reqOptions è¿è¡è¯·æ±ï¼51 *52 */53 constructor ({baseURL,method = "get",reqTransforms = [],resTransforms = [],headers,mainData,mainDataGet,successPrompt,failPrompt,showLoading = true,loadText,dependent = false,dependentPro,dependResultHandle}) {54 this.baseURL = baseURL ;55 this.method = method ;56 this.reqTransforms = reqTransforms ;57 this.resTransforms = resTransforms ;58 this.mainDataGet = mainDataGet ;59 this.successPrompt = successPrompt ;60 this.failPrompt = failPrompt ;61 this.mainData = mainData ;62 this.headers = headers ;63 this.showLoading = showLoading ;64 this.loadText = loadText ;65 //mark: æ°å 66 this.dependent = dependent ;67 this.dependentPro = dependentPro ;68 this.dependResultHandle = dependResultHandle ;69 }70 set headers(newValue){71 if (newValue) {72 Object.keys(newValue).forEach(function (headerKey) {73 Object.assign(axios.defaults.headers[headerKey],newValue[headerKey]) ;74 })75 }76 }77 set mainDataGet (newValue) {78 this._mainDataGet = newValue ;79 }80 get mainDataGet () {81 if (!this._mainDataGet) {82 this._mainDataGet = function (responseData) {83 return responseData ;84 } ;85 }86 return this._mainDataGet ;87 }88 set baseURL (newValue) {89 axios.defaults.baseURL = newValue90 }91 set authorization (newValue) {92 if (newValue) {93 axios.defaults.headers.common['Authorization'] = JSON.stringify(newValue)94 }95 }96 set contentType (newValue) {97 if (newValue) {98 axios.defaults.headers.post['Content-Type'] = newValue99 }100 }101 /**102 * åé请æ±103 * @param reqOptions : Object 请æ±çé项对象ï¼104 *105 * reqOptions ä¸å¯é
ç½®çå段å¦ä¸ï¼106 *107 * reqOptions.urlPath : string urlè·¯å¾108 * reqOptions.method : string 请æ±æ¹å¼109 * reqOptions.data : Object 请æ±çæ°æ®ï¼è¿äºæ°æ®å°è¢«æ¾å
¥è¯·æ±ä½ä¸110 * reqOptions.params : Object 请æ±çåæ°ï¼è¿äºåæ°å°ä¼è¢«åºååæ¾å
¥è¯·æ±çURLåé¢111 * reqOptions.headers : Object 请æ±å¤´å¯¹è±¡112 * reqOptions.successPrompt : boolean æ¯å¦å¯ç¨å
¨å±çæåæ示ï¼113 * reqOptions.failPrompt : boolean æ¯å¯ç¨ç¨å
¨å±ç失败æ示;114 * reqOptions.mainData : boolean å½è¯·æ±æåæ¶ï¼æ¯å¦è¿åç»è¿ mainDataGet å¤çè¿çæ°æ®ï¼115 * reqOptions.showLoading : boolean æ¯å¦å¯ç¨å è½½ç¶ææ示ï¼116 * reqOptions.loadText : string å è½½çæ示ææ¬117 * @returns AxiosPromise 请æ±ç AxiosPromise 对象118 *119 */120 request(reqOptions){121 let {dependent = this.dependent} = reqOptions ;122 if (dependent) {123 return this.dependentPro.then((dependentResult)=> {124 let depReqOptions = this.dependResultHandle && this.dependResultHandle(dependentResult,reqOptions) ;125 if (depReqOptions == false ){126 return Promise.reject("请æ±è¢«ä¾èµé»æ¢ï¼")127 }else {128 depReqOptions = depReqOptions || reqOptions ;129 return this._request(depReqOptions)130 }131 });132 }else {133 return this._request(reqOptions)134 }135 }136 _request(reqOptions){137 reqOptions = this.reqTransforms.reduce(function (options,transform) {138 let newOptions = transform(options);139 return newOptions ;140 },reqOptions);141 let {urlPath,method = this.method,params,data,headers,successPrompt = this.successPrompt,failPrompt = this.failPrompt,mainData = this.mainData,showLoading = this.showLoading , loadText = this.loadText} = reqOptions ;142 let reqConfig = {143 url:urlPath,144 method:method145 };146 if (data){147 reqConfig.data = data;148 }149 if (params) {150 reqConfig.params = params;151 }152 if (headers){153 reqConfig.headers = headers;154 }155 let showLoad = showLoading && shareInst.app ;156 // console.log(urlPath);157 // console.log(urlPath.indexOf('getregdepartmentlist'));158 // console.log(urlPath.indexOf('getlatestregdepartment'));159 // console.log(urlPath.indexOf('getlatestregdoctor'));160 if (showLoad && (urlPath.indexOf('getregdepartmentlist') === -1 || urlPath.indexOf('getlatestregdepartment') === -1 || urlPath.indexOf('getlatestregdoctor') === -1)) {161 // console.log("loadinglalllalallala");162 //æ¾ç¤ºå è½½æ示å¨163 shareInst.app.$vux.loading.show(loadText);164 }165 let axiosPromise = axios(reqConfig);166 axiosPromise = axiosPromise.then((response)=> {167 response = this.resTransforms.reduce(function (res,transform) {168 let newRes = transform(res,reqOptions);169 return newRes ;170 },response);171 let respData = response.data;172 if(respData.result){173 if (successPrompt && respData.msg ){174 Toast(respData.msg);175 }176 }177 if (mainData){178 if (!respData.result) {179 throw response180 }181 return this.mainDataGet(respData);182 }else {183 return respData;184 }185 }).catch(function (error) {186 console.log("--失败--",reqOptions,error)187 let respData = ( error && error.data ) ;188 // msg = msg || error.message;189 if(respData&&(respData.result==false||respData.result==true)){190 let msg = respData.msg;191 if ( failPrompt && msg ){192 Toast(msg);193 }194 }else{195 let msg = "ç½ç»å¼å°å·®å¦!!!"196 if ( failPrompt && msg ){197 Toast(msg);198 }199 }200 let throwData = error.response || error ;201 throw throwData;202 }).finally(function () {203 if (showLoad && (urlPath.indexOf('getregdepartmentlist') === -1 || urlPath.indexOf('getlatestregdepartment') === -1 || urlPath.indexOf('getlatestregdoctor') === -1)){204 //å
³éå è½½æ示å¨205 shareInst.app.$vux.loading.hide();206 }207 });208 return axiosPromise209 }210 /**211 * åéget请æ±212 * @param getOptions : Object get请æ±çé项对象;213 *214 *215 * getOptions ä¸å¯é
ç½®çå段å¦ä¸ï¼216 *217 * getOptions.urlPath : string urlè·¯å¾218 * getOptions.params : Object 请æ±çåæ°ï¼è¿äºåæ°å°ä¼è¢«åºååæ¾å
¥è¯·æ±çURLåé¢219 * reqOptions.headers : Object 请æ±å¤´å¯¹è±¡220 * reqOptions.successPrompt : boolean æ¯å¦å¯ç¨å
¨å±çæåæ示ï¼221 * reqOptions.failPrompt : boolean æ¯å¯ç¨ç¨å
¨å±ç失败æ示;222 * reqOptions.mainData : boolean å½è¯·æ±æåæ¶ï¼æ¯å¦è¿åç»è¿ mainDataGet å¤çè¿çæ°æ®ï¼223 * reqOptions.showLoading : boolean æ¯å¦å¯ç¨å è½½ç¶ææ示ï¼224 * reqOptions.loadText : string å è½½çæ示ææ¬225 * @returns AxiosPromise 请æ±ç AxiosPromise 对象226 *227 */228 get(getOptions){229 getOptions.method = "get" ;230 return this.request(getOptions);231 }232 /**233 * åépost请æ±234 * @param postOptions235 *236 * postOptions ä¸å¯é
ç½®çå段å¦ä¸ï¼237 *238 * postOptions.urlPath : string urlè·¯å¾239 * postOptions.data : Object 请æ±çæ°æ®ï¼è¿äºæ°æ®å°è¢«æ¾å
¥è¯·æ±ä½ä¸240 * postOptions.params : Object 请æ±çåæ°ï¼è¿äºåæ°å°ä¼è¢«åºååæ¾å
¥è¯·æ±çURLåé¢241 * postOptions.contentType : string 请æ±å¤´ç'Content-Type'å段çå¼242 * postOptions.headers : Object 请æ±å¤´å¯¹è±¡243 * postOptions.successPrompt : boolean æ¯å¦å¯ç¨å
¨å±çæåæ示ï¼244 * postOptions.failPrompt : boolean æ¯å¯ç¨ç¨å
¨å±ç失败æ示;245 * postOptions.mainData : boolean å½è¯·æ±æåæ¶ï¼æ¯å¦è¿åç»è¿ mainDataGet å¤çè¿çæ°æ®ï¼246 * reqOptions.showLoading : boolean æ¯å¦å¯ç¨å è½½ç¶ææ示ï¼247 * reqOptions.loadText : string å è½½çæ示ææ¬248 * @returns AxiosPromise 请æ±ç AxiosPromise 对象249 *250 */251 post(postOptions){252 let {contentType,...reqOptions} = postOptions;253 if (contentType) {254 reqOptions.headers = {...reqOptions.headers,'Content-Type':contentType} ;255 }256 reqOptions.method = "post" ;257 return this.request(reqOptions);258 }259 uploadFile(postOptions){260 return axios.post(postOptions.urlPath,postOptions.data,{261 headers:{262 'Content-Type': 'multipart/form-data'263 }264 })265 }266}...
data.service.ts
Source:data.service.ts
1import { Injectable } from "@angular/core";2import {3 HttpClient,4 HttpHeaders,5 HttpParams,6 HttpErrorResponse7} from "@angular/common/http";8import { environment } from "../../../environments/environment"9import { ConfigurationConstants } from "../constants/configuration-constants";10import { ResolveData } from "@angular/router";11import { DataServiceOptions } from "../models/data-service-options";12import { Utils } from '../helpers/utils';13import { ErrorCodesConstants } from '../constants/error-code-constant';14import { AppNotificationService } from './app-notification.service';15//import { NotificationService } from './notification-service';16@Injectable({17 providedIn: "root"18})19export class DataService {20 private baseUrl: string;21 paymentUrl: string;22 private masterUrl: string;23 private ssoUrl: string;24 private baseStartUrl: string;25 private role: string;26 private userId: string;27 private orgId: string;28 constructor(29 private http: HttpClient,30 private notifier: AppNotificationService,31 ) {32 // this.baseUrl = environment.url + "/";33 // this.masterUrl = environment.masterUrl + "/";34 // this.ssoUrl = environment.ssoUrl + "/";35 this.baseStartUrl = Utils.baseUrl();36 this.baseUrl = this.baseStartUrl + "im/";37 this.masterUrl = this.baseStartUrl + "mm/";38 this.ssoUrl = this.baseStartUrl + "sso/";39 this.role = localStorage.getItem("role");40 this.userId = localStorage.getItem("userId");41 this.orgId = localStorage.getItem("orgId");42 this.paymentUrl = Utils.paymentUrl() + 'payment/';43 }44 getRequest(45 url: string,46 params: HttpParams = new HttpParams(),47 reqOptions: DataServiceOptions = null48 ): ResolveData {49 let headers = new HttpHeaders();50 headers = headers.append("Access-Control-Allow-Origin", "*");51 headers = headers.append("accept", "*/*");52 if (reqOptions) {53 if (reqOptions.skipLoader) {54 headers = headers.append(55 ConfigurationConstants.HEADER_SKIP_LOADER,56 "1"57 );58 }59 if (reqOptions.cache) {60 headers = headers.append(61 ConfigurationConstants.HEADER_CACHE_REQUEST,62 "1"63 );64 }65 if (reqOptions.headers) {66 const hdrs = reqOptions.headers.split(",");67 headers = headers.append(hdrs[0], hdrs[1]);68 }69 }70 const requestUrl =71 reqOptions && reqOptions.requestURL72 ? reqOptions.requestURL73 : this.baseUrl;74 const options = { params, headers };75 return this.http76 .get(requestUrl + url, options)77 .toPromise()78 .then(79 res => res,80 err =>81 this.handleError(err)82 );83 }84 sendPostRequest(85 url: string,86 params: any,87 reqOptions: DataServiceOptions = null88 ): Promise<any> {89 let headers = new HttpHeaders();90 headers = headers.append("Access-Control-Allow-Origin", "*");91 headers = headers.append("accept", "*/*");92 if (reqOptions) {93 if (reqOptions.skipLoader) {94 headers = headers.append(95 ConfigurationConstants.HEADER_SKIP_LOADER,96 "1"97 );98 }99 if (reqOptions.cache) {100 headers = headers.append(101 ConfigurationConstants.HEADER_CACHE_REQUEST,102 "1"103 );104 }105 if (reqOptions.headers) {106 const hdrs = reqOptions.headers.split(",");107 headers = headers.append(hdrs[0], hdrs[1]);108 }109 }110 const requestUrl =111 reqOptions && reqOptions.requestURL112 ? reqOptions.requestURL113 : this.baseUrl;114 const options = { headers };115 return this.http116 .post(requestUrl + url, params, options)117 .toPromise()118 .then(119 res => res as any,120 err =>121 this.handleError(err)122 );123 }124 sendPutRequest(125 url: string,126 params: any,127 reqOptions: DataServiceOptions = null128 ): Promise<any> {129 // LoggerService.debug(url, params);130 let headers = new HttpHeaders();131 if (reqOptions) {132 if (reqOptions.skipLoader) {133 headers = headers.append(134 ConfigurationConstants.HEADER_SKIP_LOADER,135 "1"136 );137 }138 }139 const reqURL =140 reqOptions && reqOptions.requestURL141 ? reqOptions.requestURL142 : this.baseUrl;143 return this.http144 .put(reqURL + url, params, { headers: headers })145 .toPromise()146 .then(147 res => res as any,148 err =>149 this.handleError(err)150 );151 }152 sendDeleteRequest(153 url: string,154 params: any,155 reqOptions: DataServiceOptions = null156 ): Promise<any> {157 // LoggerService.debug(url, params);158 let headers = new HttpHeaders();159 headers = headers.append("Access-Control-Allow-Origin", "*");160 headers = headers.append("accept", "*/*");161 if (reqOptions) {162 if (reqOptions.skipLoader) {163 headers = headers.append(164 ConfigurationConstants.HEADER_SKIP_LOADER,165 "1"166 );167 }168 }169 const reqURL =170 reqOptions && reqOptions.requestURL171 ? reqOptions.requestURL172 : this.baseUrl;173 return this.http174 .delete(reqURL + url, { headers: headers, params: params })175 .toPromise()176 .then(177 res => res as any,178 err =>179 this.handleError(err)180 );181 }182 getRequestMaster(183 url: string,184 params: HttpParams = new HttpParams(),185 reqOptions: DataServiceOptions = null186 ): ResolveData {187 let headers = new HttpHeaders();188 headers = headers.append("Access-Control-Allow-Origin", "*");189 headers = headers.append("accept", "*/*");190 headers = headers.append("Authorization", "admin");191 if (reqOptions) {192 if (reqOptions.skipLoader) {193 headers = headers.append(194 ConfigurationConstants.HEADER_SKIP_LOADER,195 "1"196 );197 }198 if (reqOptions.cache) {199 headers = headers.append(200 ConfigurationConstants.HEADER_CACHE_REQUEST,201 "1"202 );203 }204 if (reqOptions.headers) {205 const hdrs = reqOptions.headers.split(",");206 headers = headers.append(hdrs[0], hdrs[1]);207 }208 }209 const requestUrl =210 reqOptions && reqOptions.requestURL211 ? reqOptions.requestURL212 : this.masterUrl;213 const options = { params, headers };214 return this.http215 .get(requestUrl + url, options)216 .toPromise()217 .then(218 res => res,219 err =>220 this.handleError(err)221 );222 }223 sendPostRequestSso(224 url: string,225 params: any,226 reqOptions: DataServiceOptions = null227 ): Promise<any> {228 let headers = new HttpHeaders();229 headers = headers.append("accept", "*/*");230 //headers = headers.append( 'Authorization', 'admin');231 headers = headers.append(232 "Authorization",233 "Basic " + btoa("fooClientIdPassword:secret")234 );235 if (reqOptions) {236 if (reqOptions.skipLoader) {237 headers = headers.append(238 ConfigurationConstants.HEADER_SKIP_LOADER,239 "1"240 );241 }242 if (reqOptions.cache) {243 headers = headers.append(244 ConfigurationConstants.HEADER_CACHE_REQUEST,245 "1"246 );247 }248 if (reqOptions.headers) {249 const hdrs = reqOptions.headers.split(",");250 headers = headers.append(hdrs[0], hdrs[1]);251 }252 }253 const requestUrl =254 reqOptions && reqOptions.requestURL ? reqOptions.requestURL : this.ssoUrl;255 const options = { headers };256 return this.http257 .post(requestUrl + url, params, options)258 .toPromise()259 .then(260 res => res as any,261 err =>262 this.handleError(err)263 );264 }265 sendPostRequestSsoEncodedUrl(266 url: string,267 params: any,268 reqOptions: DataServiceOptions = null269 ): Promise<any> {270 let headers = new HttpHeaders();271 headers = headers.append(272 "Authorization",273 "Basic " + btoa("fooClientIdPassword:secret")274 );275 headers = headers.append(276 "Content-type",277 "application/x-www-form-urlencoded; charset=utf-8"278 );279 if (reqOptions) {280 if (reqOptions.skipLoader) {281 headers = headers.append(282 ConfigurationConstants.HEADER_SKIP_LOADER,283 "1"284 );285 }286 if (reqOptions.cache) {287 headers = headers.append(288 ConfigurationConstants.HEADER_CACHE_REQUEST,289 "1"290 );291 }292 if (reqOptions.headers) {293 const hdrs = reqOptions.headers.split(",");294 headers = headers.append(hdrs[0], hdrs[1]);295 }296 }297 const requestUrl =298 reqOptions && reqOptions.requestURL ? reqOptions.requestURL : this.ssoUrl;299 const options = { headers };300 return this.http301 .post(requestUrl + url, params, options)302 .toPromise()303 .then(304 res => res as any,305 err =>306 this.handleError(err)307 );308 }309 resetPasswordSSOPOST(310 url: string,311 params: any,312 reqOptions: DataServiceOptions = null313 ): Promise<any> {314 let headers = new HttpHeaders();315 let ssotoken = localStorage.getItem('SSO_ACCESS_TOKEN');316 headers = headers.append("accept", "*/*");317 //headers = headers.append( 'Authorization', 'admin');318 headers = headers.append(319 "Authorization",320 "Bearer " + ssotoken321 );322 if (reqOptions) {323 if (reqOptions.skipLoader) {324 headers = headers.append(325 ConfigurationConstants.HEADER_SKIP_LOADER,326 "1"327 );328 }329 if (reqOptions.cache) {330 headers = headers.append(331 ConfigurationConstants.HEADER_CACHE_REQUEST,332 "1"333 );334 }335 if (reqOptions.headers) {336 const hdrs = reqOptions.headers.split(",");337 headers = headers.append(hdrs[0], hdrs[1]);338 }339 }340 const requestUrl =341 reqOptions && reqOptions.requestURL ? reqOptions.requestURL : this.ssoUrl;342 const options = { headers };343 return this.http344 .post(requestUrl + url, params, options)345 .toPromise()346 .then(347 res => res as any,348 err =>349 this.handleError(err)350 );351 }352 private handleError(err: HttpErrorResponse) {353 if ((!window.navigator.onLine) || ((typeof err === 'object') && (err.status === ErrorCodesConstants.ERROR_HTTP_NO_RESPONSE))) {354 this.notifier.snack('INTERNET CONNECTION ISSUE');355 } else if (err.status === ErrorCodesConstants.ERROR_HTTP_NOT_FOUND || ErrorCodesConstants.ERROR_HTTP_SERVER_ISSUE) {356 this.notifier.snack('Something went wrong')357 throw (err.error)358 } else if (err.status === ErrorCodesConstants.ERROR_HTTP_UNAUTHORIZED) {359 if (err.url.includes('sso/oauth/token')) {360 throw (err.error)361 } else {362 this.notifier.snack(err.error.error.toUpperCase())363 console.log(`Error Staus:${err.status} Error Message:${err.message} Url:${err.url}`)364 }365 } else if (err.status === ErrorCodesConstants.ERROR_HTTP_UNAUTHORIZED_ROLE) {366 this.notifier.snack(err.error.data, 6000)367 console.log(`Error Staus:${err.status} Error Message:${err.message} Url:${err.url}`)368 localStorage.clear();369 window.location.reload();370 }371 // else if (err.status === ErrorCodesConstants.ERROR_HTTP_SERVER_ISSUE) {372 // this.notifier.snack("Something went wrong")373 // throw (err.error)374 // }375 else {376 throw (err.error)377 }378 }...
apiRequest.js
Source:apiRequest.js
1import _ from 'lodash';2import urlAssembler from 'url-assembler';3import { ApiError } from './ApiError';4function extractResponseData(response) {5 return _.pick(response, [6 'status',7 'statusText',8 'url',9 'headers',10 'ok',11 ]);12}13function handleStatusCodeError(response) {14 if (!response.ok) {15 throw new ApiError(response.statusText || 'Request error', response);16 }17 return response;18}19function handleJson(response) {20 let resBody = response.body;21 try {22 resBody = JSON.parse(resBody);23 } catch (e) {24 // Failed to parse json25 }26 return {27 ...response,28 body: resBody,29 };30}31export default function(params = {}) {32 const reqOptions = params;33 const base = _.get(reqOptions, 'base', null);34 const path = _.get(reqOptions, 'path', null);35 const uriParams = _.get(reqOptions, 'uriParams', {});36 const qs = _.get(reqOptions, 'qs', {});37 const json = _.get(reqOptions, 'json', true);38 const blob = _.get(reqOptions, 'blob', false);39 const body = _.get(reqOptions, 'body', {});40 const uri = urlAssembler(base)41 .segment(path)42 .param(uriParams)43 .query(qs);44 _.merge(reqOptions, {45 headers: {46 Accept: 'application/json',47 },48 mode: 'cors',49 });50 if (json && !_.get(reqOptions.headers, 'Content-Type')) {51 _.set(reqOptions, 'headers.Content-Type', 'application/json');52 }53 if (!json && !_.get(reqOptions.headers, 'Content-Type')) {54 _.unset(reqOptions.headers, 'Content-Type');55 }56 if (json) {57 if (_.isEmpty(body)) {58 // unset body if it's not a valid json,59 // it's neccesary especially for IE browsers which empty object literal convert60 // to [Object object] string instead of serializing it61 reqOptions.body = undefined;62 } else {63 reqOptions.body = JSON.stringify(body);64 }65 } else {66 reqOptions.body = body;67 }68 return fetch(uri.toString(), reqOptions)69 .then(70 response => Promise.all([71 extractResponseData(response),72 blob ? response.blob() : response.text(),73 ]),74 )75 .then(76 promised => ({77 ...promised[0],78 body: promised[1],79 }),80 )81 .then(blob ? _.identity : handleJson)82 .then(handleStatusCodeError)83 .then((x) => {84 if (reqOptions.resolveWithFullResponse) {85 return x;86 }87 return x.body;88 });...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!