How to use handleHeaders method in wpt

Best JavaScript code snippet using wpt

api-connection.service.ts

Source:api-connection.service.ts Github

copy

Full Screen

...61 }62 cookie_remove(name: string): void {63 this.cookie_write(name, undefined, -1);64 }65 handleHeaders(password?: string) {66 // NOTE: This needs to be in each api, so that is updated as soon as logged in67 const _headers = { 'API-VERSION': this.version };68 // NOTE: This needs to be in each api, so that is updated as soon as logged in69 const session_id = this.cookie_read('was_session_id');70 if (session_id) {71 _headers['WAS-SESSION'] = session_id;72 }73 if (password) {74 _headers['Authorization1'] = `Basic ${this.b64EncodeUnicode(password)}`;75 }76 this.apiHeaders = new HttpHeaders(_headers);77 }78 // THE OBSERVABLE WAY //79 private handleError(error: HttpErrorResponse) {80 let errMsg: string;81 console.error('WASAPI: handleError', error);82 if (error.error instanceof Error) {83 // A client-side or network error occurred.84 // http://stackoverflow.com/questions/39571231/how-to-check-whether-user-has-internet-connection-or-not-in-angular285 if (navigator.onLine) {86 errMsg = `${error.status} - ${error.statusText || ''} ${error.error.message}`;87 } else {88 errMsg = 'There is no Internet connection.';89 }90 } else {91 if (navigator.onLine) {92 // The backend returned an unsuccessful response code.93 // {"error": {"message": string, code: number}} // where code is a http status code as-well as an internal error code.94 try {95 const _checkIfValue = function (_obj: any, _key: string) {96 if (_obj.hasOwnProperty(_key) && (_obj[_key] !== undefined && _obj[_key] !== null)) {97 return true;98 } else {99 return false;100 }101 };102 if (_checkIfValue(error, 'error') && _checkIfValue(error.error, 'error') && _checkIfValue(error.error.error, 'message')) {103 errMsg = error.error.error.message; // JSON.parse(error.error)104 // Catch 419 session expired error that will be returned on invalid session id105 // FOR NOW, ONLY HANDLE THE SESSION EXPIRED CASE106 // if (errorObj.error.code === 419) {107 // this.dialog.open(WasAlert, {108 // data: { title: 'Attention', body: error, buttons: ['Login', 'Cancel'] }109 // }).afterClosed().subscribe(result => {110 // // result is the index of the button pressed111 // if (result === 0) {112 // console.log('Open SSO'); // After SSO is a dialog, simply open right here113 // }114 // });115 // }116 } else if (_checkIfValue(error, 'message')) {117 errMsg = error.message;118 } else {119 errMsg = error.statusText;120 }121 } catch (locerror) {122 // TODO: Log these type of errors to server. TODO: Create server logger.123 // errMsg = locerror.toString();124 errMsg = error.statusText;125 console.error('API: + LOCAL Error:', error, locerror);126 }127 } else {128 errMsg = 'There is no Internet connection.';129 }130 }131 // TODO: observableThrowError(new Error(errMsg));132 return observableThrowError(errMsg);133 }134 private extractData(res: any) {135 const body = res.data;136 // Add http status to body //137 body.status = res.status;138 try {139 if (body.hasOwnProperty('special_message')) {140 console.log(`ApiConnectionService: extractData: special_message:[${body.special_message}]`);141 // this.dialog.open(WasAlert, {142 // data: { title: body.special_message.title, body: body.special_message.message }143 // });144 }145 } catch (extractError) {146 console.error('extractData', extractError);147 }148 return body;149 }150 private extractVerifyData(res: any) {151 const body = res.data;152 // Add http status to body //153 body.status = res.status;154 console.log('set session id', body.session_id);155 try {156 this.cookie_write('was_session_id', body.session_id);157 if (body.hasOwnProperty('special_message')) {158 console.log(`ApiConnectionService: extractData: special_message:[${body.special_message}]`);159 // this.dialog.open(WasAlert, {160 // data: { title: body.special_message.title, body: body.special_message.message }161 // });162 }163 } catch (extractError) {164 console.error('extractVerifyData', extractError);165 }166 return body;167 }168 // https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem169 b64EncodeUnicode(str: string): string {170 // first we use encodeURIComponent to get percent-encoded UTF-8,171 // then we convert the percent encodings into raw bytes which172 // can be fed into btoa.173 return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,174 function toSolidBytes(match, p1) {175 return String.fromCharCode(Number('0x' + p1));176 }));177 }178 encode_query_string(_obj): string {179 // http://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object180 const q_str = [];181 for (const _p in _obj) {182 if (_obj.hasOwnProperty(_p)) {183 q_str.push(encodeURIComponent(_p) + '=' + encodeURIComponent(_obj[_p]));184 }185 }186 return q_str.join('&');187 }188 // Creates or updates person, returns person info189 // person info also includes inapps and app settings190 createPerson(apiobject: any): Observable<any> {191 this.handleHeaders();192 // NOTE: Use share to avoid duplicate calls193 return this.http.post(this.person_url, apiobject, { headers: this.apiHeaders, withCredentials: true }).pipe(194 map((res: any) => {195 return this.extractData(res);196 }), catchError(this.handleError), share());197 }198 /**199 * Return a list of newsfeed items.200 *201 * @param _params {"user_id": string}202 */203 getNewsfeed(_params: any): Observable<any> {204 this.handleHeaders();205 const _query_string = this.encode_query_string(_params);206 return this.http.get(`${this.personNewsUrl}?${_query_string}`, { headers: this.apiHeaders }).pipe(207 map((res: any) => {208 return this.extractData(res);209 }), catchError(this.handleError), share());210 }211 /**212 * Add an action to another user e.g. show an alert to the other person.213 *214 * @param user_id215 * @param to_username216 * @param news_ids217 * @param [global_news_ids]218 */219 setNewsfeed(user_id: string, to_username: string, action: string): Observable<any> {220 this.handleHeaders();221 const apiobject = { user_id, to_username, action };222 return this.http.post(this.personNewsUrl, apiobject, { headers: this.apiHeaders, withCredentials: true }).pipe(223 map((res: any) => {224 return this.extractData(res);225 }), catchError(this.handleError), share());226 }227 /**228 * Sets news items as seen.229 *230 * @param user_id231 * @param news_ids232 * @param [global_news_ids]233 */234 seenNewsfeed(user_id: string, news_ids: string[], global_news_ids?: number[]): Observable<any> {235 this.handleHeaders();236 const apiobject = { user_id, news_ids };237 if (global_news_ids) {238 apiobject['global_news_ids'] = global_news_ids;239 }240 return this.http.post(this.personNewsSeenUrl, apiobject, { headers: this.apiHeaders, withCredentials: true }).pipe(241 map((res: any) => {242 return this.extractData(res);243 }), catchError(this.handleError), share());244 }245 /**246 * Return a list of favorite apps.247 *248 * @param [_params] {"user_id": string}249 * @returns Success or failure status code and message. {favorites:[{app},...]}250 */251 checkFavorite(_params?: any): Observable<any> {252 this.handleHeaders();253 const _query_string = this.encode_query_string(_params);254 return this.http.get(`${this.check_favorite_url}?${_query_string}`, { headers: this.apiHeaders }).pipe(255 map((res: any) => {256 return this.extractData(res);257 }), catchError(this.handleError), share());258 }259 /**260 * Return a list of favorite apps.261 *262 * @param [_params] {"user_id": string}263 * @returns Success or failure status code and message. {favorites:[{app},...]}264 */265 getFavorites(_params?: any): Observable<any> {266 this.handleHeaders();267 const _query_string = this.encode_query_string(_params);268 return this.http.get(`${this.favorites_url}?${_query_string}`, { headers: this.apiHeaders }).pipe(269 map((res: any) => {270 return this.extractData(res).favorites;271 }), catchError(this.handleError), share());272 }273 /**274 * Add an app to list of favorite apps.275 *276 * @param user_id The user id.277 * @param [storeapp_id] This is only sent in from WickeyAppStore (on actual app sites it uses the hostname).278 * @returns Success or failure status code and message. {favorites:[{app},...]}279 */280 setFavorite(user_id: string, storeapp_id?: number): Observable<any> {281 this.handleHeaders();282 const apiobject = { user_id: user_id };283 if (storeapp_id) {284 apiobject['storeapp_id'] = storeapp_id;285 }286 // NOTE: Use share to avoid duplicate calls287 return this.http.post(this.favorites_url, apiobject, { headers: this.apiHeaders, withCredentials: true }).pipe(288 map((res: any) => {289 return this.extractData(res).favorites;290 }), catchError(this.handleError), share());291 }292 /**293 * Remove an app from the list of favorite apps.294 *295 * @param user_id The user id.296 * @param [storeapp_id] This is only sent in from WickeyAppStore (on actual app sites it uses the hostname).297 * @returns Success or failure status code and message. {favorites:[{app},...]}298 */299 deleteFavorite(user_id: string, storeapp_id?: number): Observable<any> {300 this.handleHeaders();301 const apiobject = { user_id: user_id };302 if (storeapp_id) {303 apiobject['storeapp_id'] = storeapp_id;304 }305 // NOTE: Use share to avoid duplicate calls306 return this.http.post(this.fav_del_url, apiobject, { headers: this.apiHeaders, withCredentials: true }).pipe(307 map((res: any) => {308 return this.extractData(res).favorites;309 }), catchError(this.handleError), share());310 }311 // Sends the email a recovery token312 tokenPerson(email: string, user_id: string): Observable<any> {313 this.handleHeaders();314 // NOTE: Use share to avoid duplicate calls315 return this.http.post(this.person_recover_token_url, { email: email, user_id: user_id },316 { headers: this.apiHeaders, withCredentials: true }).pipe(317 map(this.extractData),318 catchError(this.handleError), share());319 }320 // Verify the recovery token321 verifyPerson(email: string, user_id: string, verification_token: string, version?: number, password?: string): Observable<any> {322 if (password) {323 this.handleHeaders(password);324 } else {325 this.handleHeaders();326 }327 // DEPRECATE version parameter328 this.handleHeaders();329 // NOTE: Use share to avoid duplicate calls330 return this.http.post(this.person_recover_verify_url,331 { email: email, user_id: user_id, verification_token: verification_token }, { headers: this.apiHeaders, withCredentials: true }).pipe(332 map((res: any) => {333 return this.extractVerifyData(res);334 }), catchError(this.handleError), share());335 }336 /**337 * Set or change a password of a user.338 *339 * @param user_id string: The user id.340 * @param password string: The raw password.341 * @param new_password string: OPTIONAL The new password on password changes.342 * @returns Success or failure status code and message.343 */344 authPerson(user_id: string, password: string, new_password?: string): Observable<any> {345 this.handleHeaders(password);346 const apiobject = { user_id: user_id };347 if (new_password) {348 apiobject['new_password'] = this.b64EncodeUnicode(new_password);349 }350 // NOTE: Use share to avoid duplicate calls351 return this.http.post(this.person_auth_url, apiobject, { headers: this.apiHeaders, withCredentials: true }).pipe(352 map((res: any) => {353 return this.extractData(res);354 }), catchError(this.handleError), share());355 }356 /**357 * Returns a list of reviews for a store app.358 *359 * @example360 * this.apiConnectionService.getReviews({'storeapp_id': this.selected_app.id}).subscribe((_reviews: any) => { });361 * @param _params {"storeapp_id": number}: OPTIONAL storeapp_id (id of the storeapp)362 * @returns List of reviews [{"id":number,"title":string,"text":string,"rating":number,"last_modified":number},..]363 */364 getReviews(_params?: any): Observable<[Review]> {365 this.handleHeaders();366 const _query_string = this.encode_query_string(_params);367 return this.http.get(`${this.reviews_url}?${_query_string}`, { headers: this.apiHeaders }).pipe(368 map((res: any) => {369 return this.extractData(res).reviews;370 }), catchError(this.handleError), share());371 }372 /**373 * Creates a new review or edits an existing one.374 *375 * @example376 * this.apiConnectionService.setReview({'user_id':string,'title':string,'text':string,'rating':number}).subscribe((_data: any) => { });377 * @param _review {'user_id':string,'title':string,'text':string,'rating':number}378 */379 setReview(_params: any): Observable<any> {380 this.handleHeaders();381 return this.http.post(this.reviews_url, _params, { headers: this.apiHeaders, withCredentials: true }).pipe(382 map((res: any) => {383 return this.extractData(res);384 }), catchError(this.handleError), share());385 }386 /**387 * Returns a list of inapps for the app.388 *389 * @example390 * this.apiConnectionService.getInapps().subscribe((_inapps: any) => { });391 * @param [_params] {user_id: <string>}.392 * @returns List of inapps393 */394 getInapps(_params?: any): Observable<any> {395 this.handleHeaders();396 const _query_string = this.encode_query_string(_params);397 return this.http.get(`${this.purchases_url}?${_query_string}`, { headers: this.apiHeaders }).pipe(398 map((res: any) => {399 return this.extractData(res);400 }), catchError(this.handleError), share());401 }402 /**403 * Creates a new purchase.404 *405 * @example406 * this.apiConnectionService.setPurchase(407 * {'user_id':string,'purchase_id':string,'receipt':string,'pay_amount':number,'email':string,'first_name':string,408 * 'last_name':string,'zip_code':string,'apple_wallet_token'?:string}409 * ).subscribe((_data: any) => { });410 * @param _params {*}: The parameters listed in the example.411 * @returns Returns a standard user object (same as createPerson)412 */413 setPurchase(_params: any): Observable<any> {414 this.handleHeaders();415 return this.http.post(this.purchases_url, _params, { headers: this.apiHeaders, withCredentials: true }).pipe(416 map(this.extractData),417 catchError(this.handleError), share());418 }419 /**420 * Consumes coins recieved from purchases or videos.421 *422 * @example423 * this.apiConnectionService.consumeCoins({'user_id':string,'coins':number,'reason'?:string}).subscribe((_data: any) => { });424 * @param _params {user_id: string, coins: number, reason?: string}425 * @returns Returns a standard user object (same as createPerson)426 */427 consumeCoins(_params: { user_id: string, coins: number, reason?: string }): Observable<any> {428 this.handleHeaders();429 return this.http.post(this.consumeUrl, _params, { headers: this.apiHeaders, withCredentials: true }).pipe(430 map(this.extractData),431 catchError(this.handleError), share());432 }433 /**434 * Returns a BlueSnap hosted field token435 */436 getBluesnapToken(): Observable<{ token: string }> {437 return this.http.post(this.bluesnapTokenUrl, {}).pipe(438 map((res: any) => {439 return this.extractData(res);440 }), catchError(this.handleError), share());441 }442 /**443 * Returns an encrypted shopper token in `token`, post to to BlueSnap via `enc=this_returned_token`444 */445 getBluesnapShopper(_shopper_id: number): Observable<{ token: string }> {446 return this.http.post(this.bluesnapShopperUrl, { shopper_id: _shopper_id }).pipe(447 map((res: any) => {448 return this.extractData(res);449 }), catchError(this.handleError), share());450 }451 /**452 * Returns a BlueSnap Wallet token. (Used with ApplePay)453 * https://developers.bluesnap.com/v8976-Basics/docs/apple-pay#section-step-4-verify-your-domain454 *455 * @param _validation_url The `event.validationURL` from the BlueSnap onvalidatemerchant callback456 * @returns the auth token, an object.457 */458 getBluesnapWallet(_validation_url: string): Observable<{ token: string }> {459 return this.http.post(this.bluesnapWalletUrl, { validation_url: _validation_url }).pipe(460 map((res: any) => {461 return res;462 }), catchError(this.handleError), share());463 }464 /**465 * Notifies the server that a video ad has started by this user and video id.466 */467 adVideoStart(user_id: string, video_id: string): Observable<any> {468 this.handleHeaders();469 return this.http.post(this.adVideoStartUrl, { user_id: user_id, video_id: video_id },470 { headers: this.apiHeaders }).pipe(471 map((res: any) => {472 return this.extractData(res);473 }), catchError(this.handleError), share());474 }475 /**476 * Notifies the server that a video ad has ended by this user and video id.477 */478 adVideoEnd(user_id: string, video_id: string): Observable<any> {479 this.handleHeaders();480 return this.http.post(this.adVideoEndUrl, { user_id: user_id, video_id: video_id }, { headers: this.apiHeaders }).pipe(481 map((res: any) => {482 return this.extractData(res);483 }), catchError(this.handleError), share());484 }485 /**486 * Gets a value(s) for requested key(s).487 *488 * @example489 * this.apiConnectionService.getWASStore(490 * {'user_id':string,'keys':string}491 * ).subscribe((_data: any) => { });492 * @param _params string: user_id, string: keys where keys is a single key or a comma separated string of keys (keys='key1,')493 * @returns Returns a standard user object with was_data.494 */495 getWASStore(_params: { user_id: string, keys: string }): Observable<{}> {496 this.handleHeaders();497 // NOTE: Use share to avoid duplicate calls498 const _query_string = this.encode_query_string(_params);499 return this.http.get(`${this.wasstore_url}?${_query_string}`, { headers: this.apiHeaders }).pipe(500 map((res: any) => {501 return this.extractData(res).was_data;502 }), catchError(this.handleError), share());503 }504 /**505 * Stores/Updates all values to respective key in passed in json was_data.506 *507 * @example508 * this.apiConnectionService.setWASStore(509 * {'user_id':string,'was_data':{key:value,...}}510 * ).subscribe((_data: any) => { });511 * @param _params string: user_id, json: was_data where was_data is format {key:value,...}512 * @returns Returns a standard user object with was_data.513 */514 setWASStore(_params: { user_id: string, was_data: {} }): Observable<any> {515 this.handleHeaders();516 // NOTE: Use share to avoid duplicate calls517 return this.http.post(this.wasstore_url, _params, { headers: this.apiHeaders, withCredentials: true }).pipe(518 map((res: any) => {519 return this.extractData(res);520 }), catchError(this.handleError), share());521 }522 /**523 * Deletes a value(s) for the requested key(s).524 *525 * @example526 * this.apiConnectionService.deleteWASStore(527 * {'user_id':string,'keys':string}528 * ).subscribe((_data: any) => { });529 * @param _params string: user_id, string: keys where keys is a single key or a comma separated string of keys (keys='key1,')530 * @returns Returns a standard user object.531 */532 deleteWASStore(_params: { user_id: string, keys: string }): Observable<any> {533 this.handleHeaders();534 // NOTE: Use share to avoid duplicate calls535 const _query_string = this.encode_query_string(_params);536 return this.http.delete(`${this.wasstore_url}?${_query_string}`, { headers: this.apiHeaders, withCredentials: true }).pipe(537 map((res: any) => {538 return this.extractData(res);539 }), catchError(this.handleError), share());540 }541 /**542 * Get the leaderboard for app. Optional pass in username to return rank of user.543 *544 * @example545 * this.apiConnectionService.getLeaderboard().subscribe((_data: any) => { });546 * @param _params string: username,547 * @returns Returns a leaderboard list (optional: and score and rank of passed in username).548 */549 getLeaderboard(_params: { username?: string }): Observable<{550 leaderboard: [any], rank?: number, score?: number,551 name?: string, icon?: string552 }> {553 this.handleHeaders();554 // NOTE: Use share to avoid duplicate calls555 const _query_string = this.encode_query_string(_params);556 return this.http.get(`${this.leaderboardUrl}?${_query_string}`, { headers: this.apiHeaders }).pipe(557 map((res: any) => {558 return this.extractData(res);559 }), catchError(this.handleError), share());560 }561 /**562 * Stores/Updates the highscore of user.563 *564 * @example565 * this.apiConnectionService.setHighscore(566 * {'user_id':string,'highscore':number}567 * ).subscribe((_data: any) => { });568 * @param _params string: user_id, json: was_data where was_data is format {key:value,...}569 * @returns Returns rank of user.570 */571 setHighscore(_params: { user_id: string, highscore: number }): Observable<{ status: number, rank?: number }> {572 this.handleHeaders();573 // NOTE: Use share to avoid duplicate calls574 return this.http.post(this.highscoreUrl, _params, { headers: this.apiHeaders, withCredentials: true }).pipe(575 map((res: any) => {576 return this.extractData(res);577 }), catchError(this.handleError), share());578 }...

Full Screen

Full Screen

http.service.ts

Source:http.service.ts Github

copy

Full Screen

...11 constructor(private http: HttpClient) { }1213 get(api: any): Observable<any> {14 let url: string = environment.baseUrl + api;15 let httpOptions = { headers: this.handleHeaders() };16 return this.http.get(url, httpOptions)17 .pipe(catchError(this.handleError));18 }1920 post(api: any, model: any): Observable<any> {21 let url: string = environment.baseUrl + api;22 let httpOptions = { headers: this.handleHeaders() };23 return this.http.post(url, model, httpOptions)24 .pipe(catchError(this.handleError));25 }2627 put(api: any, model: any): Observable<any> {28 let url: string = environment.baseUrl + api;29 let httpOptions = { headers: this.handleHeaders() };30 return this.http.put(url, model, httpOptions)31 .pipe(catchError(this.handleError));32 }3334 delete(api: any): Observable<any> {35 let url: string = environment.baseUrl + api;36 let httpOptions = { headers: this.handleHeaders() };37 return this.http.delete(url, httpOptions)38 .pipe(catchError(this.handleError));39 }4041 patch(api: any, model: any): Observable<any> {42 let url: string = environment.baseUrl + api;43 let httpOptions = { headers: this.handleHeaders() };44 return this.http.patch(url, model, httpOptions)45 .pipe(catchError(this.handleError));46 }4748 postFormData(api: any, formData: FormData): Observable<any> {49 let url: string = environment.baseUrl + api;50 let httpOptions = { headers: new HttpHeaders() };51 return this.http.post(url, formData, httpOptions)52 .pipe(catchError(this.handleError));53 }5455 getJson(api: any): Observable<any> {56 let url: string = environment.baseUrl + api;57 let httpOptions = { headers: this.handleHeaders() };58 return this.http.get(url, httpOptions)59 .pipe(map(this.extractData), catchError(this.handleError));60 }6162 postJson(api: any, model: any): Observable<any> {63 let url: string = environment.baseUrl + api;64 let httpOptions = { headers: this.handleHeaders() };65 return this.http.post(url, model, httpOptions)66 .pipe(map(this.extractData), catchError(this.handleError));67 }6869 getConfig(url: string): Observable<any> {70 return this.http.get(url)71 .pipe(catchError(this.handleError));72 }7374 getCsv(url): Observable<any> {75 return this.http.get(url, { responseType: 'text' })76 .pipe(catchError(this.handleError));77 }7879 async asyncGet(api: string): Promise<any> {80 let url: any = environment.baseUrl + api;81 try {82 let response = await this.http.get(url).toPromise();83 return response;84 } catch (error) {85 await this.handleError(error);86 }87 }8889 getData(api: any, dataType: string): Observable<any> {90 let url: any = environment.baseUrl + api;91 //const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');92 let headers: any;93 if (dataType.toLowerCase() == 'json')94 headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');95 else96 headers = new HttpHeaders().set('Content-Type', 'csv/plain; charset=utf-8');9798 return this.http.get(url, { headers, responseType: 'text' }).pipe(catchError(this.handleError));99 //return this.http.get(url, { headers }).pipe(catchError(this.handleError));100 }101102 getExcelData(api: any): Observable<any> {103 let url: any = environment.baseUrl + api;104 let headers: any;105 headers = new HttpHeaders().set('Content-Type', 'application/vnd.ms-excel');106 return this.http.get(url, { headers, responseType: 'blob' }).pipe(catchError(this.handleError));107 }108109 postData(api: any, model: any): Observable<any> {110 let url: string = environment.baseUrl + api;111 return this.http.post(url, model, { headers: this.handleHeaders(), responseType: 'text' })112 .pipe(catchError(this.handleError));113 }114115 private handleHeaders(): HttpHeaders {116 return new HttpHeaders({117 'Content-Type': 'application/json'118 });119 }120121 private handleError(error) {122 let errorMessage = '';123 if (error.error instanceof ErrorEvent) {124 errorMessage = `Error: ${error.error.message}`; // client-side error125 } else {126 errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; // server-side error127 }128 return throwError(errorMessage);129 } ...

Full Screen

Full Screen

Api.ts

Source:Api.ts Github

copy

Full Screen

...14 throw res;15 }16 return res;17}18function handleHeaders(options?: ApiOptions): HeadersInit {19 return {20 'Content-Type': 'application/json',21 ...(options?.token ? { Authorization: 'Bearer ' + options.token } : {}),22 ...(options?.headers || {}),23 };24}25function handleQueryParams(options?: ApiOptions): string {26 if (options?.locale || options?.queryParams) {27 let params = {} as { locale?: string };28 if (options?.locale) {29 params.locale = options.locale;30 }31 if (options.queryParams) {32 params = {33 ...options.queryParams,34 ...params,35 };36 }37 return `?${stringify(params)}`;38 }39 return '';40}41export const Api = {42 get: <T>(urlPath: string, options?: ApiOptions): Promise<T> => {43 return fetch(44 `${process.env.NEXT_PUBLIC_API_URL}${urlPath}${handleQueryParams(45 options,46 )}`,47 {48 method: 'GET',49 cache: 'no-cache',50 headers: handleHeaders(options),51 },52 ).then(handleResponse);53 },54 post: <T>(55 urlPath: string,56 data?: object,57 options?: ApiOptions,58 ): Promise<T> => {59 return fetch(60 `${process.env.NEXT_PUBLIC_API_URL}${urlPath}${handleQueryParams(61 options,62 )}`,63 {64 method: 'POST',65 cache: 'no-cache',66 body: JSON.stringify(data),67 headers: handleHeaders(options),68 },69 ).then(handleResponse);70 },71 put: <T>(72 urlPath: string,73 data?: object,74 options?: ApiOptions,75 ): Promise<T> => {76 return fetch(77 `${process.env.NEXT_PUBLIC_API_URL}${urlPath}${handleQueryParams(78 options,79 )}`,80 {81 method: 'PUT',82 cache: 'no-cache',83 body: JSON.stringify(data),84 headers: handleHeaders(options),85 },86 ).then(handleResponse);87 },88 patch: <T>(89 urlPath: string,90 data?: object,91 options?: ApiOptions,92 ): Promise<T> => {93 return fetch(94 `${process.env.NEXT_PUBLIC_API_URL}${urlPath}${handleQueryParams(95 options,96 )}`,97 {98 method: 'PATCH',99 cache: 'no-cache',100 body: JSON.stringify(data),101 headers: handleHeaders(options),102 },103 ).then(handleResponse);104 },105 delete: <T>(urlPath: string, options?: ApiOptions): Promise<T> => {106 return fetch(107 `${process.env.NEXT_PUBLIC_API_URL}${urlPath}${handleQueryParams(108 options,109 )}`,110 {111 method: 'DELETE',112 cache: 'no-cache',113 headers: handleHeaders(options),114 },115 ).then(handleResponse);116 },...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test submitted successfully!');5 wpt.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log('Test completed successfully!');8 console.log('View your test at: ' + data.data.summary);9 });10});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 wpt.getTestResults(data.data.testId, function(err, data) {5 if (err) return console.error(err);6 console.log(data.data.median.firstView);7 });8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11 if (err) return console.error(err);12 wpt.getTestResults(data.data.testId, function(err, data) {13 if (err) return console.error(err);14 console.log(data.data.median.firstView);15 });16});17var wpt = require('webpagetest');18var wpt = new WebPageTest('www.webpagetest.org');19 if (err) return console.error(err);20 wpt.getTestResults(data.data.testId, function(err, data) {21 if (err) return console.error(err);22 console.log(data.data.median.firstView);23 });24});25var wpt = require('webpagetest');26var wpt = new WebPageTest('www.webpagetest.org');27 if (err) return console.error(err);28 wpt.getTestResults(data.data.testId, function(err, data) {29 if (err) return console.error(err);30 console.log(data.data.median.firstView);31 });32});33var wpt = require('webpagetest');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt.js');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.log(err);4 console.log('Test submitted. Polling for results...');5 wpt.getTestResults(data.data.testId, function (err, data) {6 if (err) return console.log(err);7 console.log(data);8 });9});10### wpt.getLocations([callback])11* `location` - The location identifier (e.g. "Dulles:Chrome")12* `label` - The label to display for the location (e.g. "Dulles, VA - Chrome")13* `region` - The region identifier (e.g. "us-east")14* `regionLabel` - The label to display for the region (e.g. "United States East")15* `browser` - The browser identifier (e.g. "Chrome")16* `browserLabel` - The label to display for the browser (e.g. "Chrome")17* `lat` - The latitude of the location (e.g. 38.953)18* `lng` - The longitude of the location (e.g. -77.447)19* `default` - true if this is the default location for the region (e.g. "Dulles:Chrome" is the default location for "us-east")20var wpt = require('wpt.js');21var wpt = new WebPageTest('www.webpagetest.org');22wpt.getLocations(function (err, data) {23 if (err) return console.log(err);24 console.log(data);25});26### wpt.getTesters([callback])27* `location` - The location identifier (e.g. "Dulles:Chrome")

Full Screen

Using AI Code Generation

copy

Full Screen

1var Wpt = require('wpt');2var wpt = new Wpt('your api key');3 if (err) {4 console.log('Error: ' + err);5 } else {6 var testId = data.data.testId;7 wpt.handleHeaders(testId, function(err, data) {8 if (err) {9 console.log('Error: ' + err);10 } else {11 console.log(data);12 }13 });14 }15});16var Wpt = require('wpt');17var wpt = new Wpt('your api key');18 if (err) {19 console.log('Error: ' + err);20 } else {21 var testId = data.data.testId;22 wpt.handleRequest(testId, function(err, data) {23 if (err) {24 console.log('Error: ' + err);25 } else {26 console.log(data);27 }28 });29 }30});31var Wpt = require('wpt');32var wpt = new Wpt('your api key');33 if (err) {34 console.log('Error: ' + err);35 } else {36 var testId = data.data.testId;37 wpt.handleResponse(testId, function(err, data) {38 if (err) {39 console.log('Error: ' + err);40 } else {41 console.log(data);42 }43 });44 }45});46var Wpt = require('wpt');47var wpt = new Wpt('your api key');48 if (err) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2wpt.handleHeaders(1234, function(err, res) {3 if (err) {4 console.log(err);5 } else {6 console.log(res);7 }8});9### handleHeaders(testId, callback)10### getTestInfo(testId, callback)11### getTestResults(testId, callback)12### getTestResultsByLocation(testId, location, callback)13### getTestResultsByLocationAndConnection(testId, location, connection, callback)14### getTestResultsByLocationAndConnectionAndBrowser(testId, location, connection, browser, callback)15Callback function with parameters (err,

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful