How to use generateURLString method in wpt

Best JavaScript code snippet using wpt

http-client.service.ts

Source:http-client.service.ts Github

copy

Full Screen

1/**2 * Licensed to the Apache Software Foundation (ASF) under one3 * or more contributor license agreements. See the NOTICE file4 * distributed with this work for additional information5 * regarding copyright ownership. The ASF licenses this file6 * to you under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance8 * with the License. You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 *12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18import {Injectable} from '@angular/core';19import {Observable} from 'rxjs/Observable';20import 'rxjs/add/operator/first';21import 'rxjs/add/observable/throw';22import {23 Http, XHRBackend, Request, RequestOptions, RequestOptionsArgs, Response, Headers, URLSearchParams24} from '@angular/http';25import {HomogeneousObject} from '@app/classes/object';26import {AuditLogsListQueryParams} from '@app/classes/queries/audit-logs-query-params';27import {AuditLogsGraphQueryParams} from '@app/classes/queries/audit-logs-graph-query-params';28import {AuditLogsTopResourcesQueryParams} from '@app/classes/queries/audit-logs-top-resources-query-params';29import {ServiceLogsQueryParams} from '@app/classes/queries/service-logs-query-params';30import {ServiceLogsHistogramQueryParams} from '@app/classes/queries/service-logs-histogram-query-params';31import {ServiceLogsTruncatedQueryParams} from '@app/classes/queries/service-logs-truncated-query-params';32import {AppStateService} from '@app/services/storage/app-state.service';33@Injectable()34export class HttpClientService extends Http {35 private readonly apiPrefix = 'api/v1/';36 private readonly endPoints = {37 status: {38 url: 'status'39 },40 auditLogs: {41 url: 'audit/logs',42 params: opts => new AuditLogsListQueryParams(opts)43 },44 auditLogsGraph: {45 url: 'audit/logs/bargraph',46 params: opts => new AuditLogsGraphQueryParams(opts)47 },48 auditLogsFields: {49 url: 'audit/logs/schema/fields'50 },51 serviceLogs: {52 url: 'service/logs',53 params: opts => new ServiceLogsQueryParams(opts)54 },55 serviceLogsHistogram: {56 url: 'service/logs/histogram',57 params: opts => new ServiceLogsHistogramQueryParams(opts)58 },59 serviceLogsFields: {60 url: 'service/logs/schema/fields'61 },62 serviceLogsTruncated: {63 url: 'service/logs/truncated',64 params: opts => new ServiceLogsTruncatedQueryParams(opts)65 },66 components: {67 url: 'service/logs/components/levels/counts'68 },69 serviceComponentsName: {70 url: 'service/logs/components'71 },72 clusters: {73 url: 'service/logs/clusters'74 },75 hosts: {76 url: 'service/logs/tree'77 },78 topAuditLogsResources: {79 url: variables => `audit/logs/resources/${variables.number}`,80 params: opts => new AuditLogsTopResourcesQueryParams(opts)81 },82 logIndexFilters: {83 url: variables => `shipper/filters/${variables.clusterName}/level`84 },85 shipperClusterServiceList: {86 url: variables => `shipper/input/${variables.cluster}/services`87 },88 shipperClusterServiceConfiguration: {89 url: variables => `shipper/input/${variables.cluster}/services/${variables.service}`90 },91 shipperClusterServiceConfigurationTest: {92 url: variables => `shipper/input/${variables.cluster}/test`93 }94 };95 private readonly unauthorizedStatuses = [401, 403, 419];96 constructor(backend: XHRBackend, defaultOptions: RequestOptions, private appState: AppStateService) {97 super(backend, defaultOptions);98 }99 /**100 * The goal here is to check if the given real api url should be always POST or not.\101 * See https://issues.apache.org/jira/browse/AMBARI-23779102 * @param {string} url The full url for the api end point.103 * @returns {boolean}104 */105 private shouldTurnGetToPost(url: string): boolean {106 const subUrl = url.replace(this.apiPrefix, '');107 return /^(audit|service)/.test(subUrl);108 }109 private generateUrlString(url: string, urlVariables?: HomogeneousObject<string>): string {110 const preset = this.endPoints[url];111 let generatedUrl: string;112 if (preset) {113 const urlExpression = preset.url;114 let path: string;115 if (typeof urlExpression === 'function') {116 path = preset.url(urlVariables);117 } else if (typeof urlExpression === 'string') {118 path = preset.url;119 }120 generatedUrl = `${this.apiPrefix}${path}`;121 } else {122 generatedUrl = url;123 }124 return generatedUrl;125 }126 private generateUrl(request: string | Request): string | Request {127 if (typeof request === 'string') {128 return this.generateUrlString(request);129 }130 if (request instanceof Request) {131 request.url = this.generateUrlString(request.url);132 return request;133 }134 }135 private generateOptions(url: string, params: HomogeneousObject<string>): RequestOptionsArgs {136 const preset = this.endPoints[url],137 rawParams = preset && preset.params ? preset.params(params) : params;138 if (rawParams) {139 const paramsString = Object.keys(rawParams).map((key: string): string => `${key}=${rawParams[key]}`).join('&'),140 urlParams = new URLSearchParams(paramsString, {141 encodeKey: key => key,142 encodeValue: value => encodeURIComponent(value)143 });144 return {145 params: urlParams146 };147 } else {148 return {149 params: rawParams150 };151 }152 }153 request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {154 const handleResponseError = (error) => {155 let handled = false;156 if (this.unauthorizedStatuses.indexOf(error.status) > -1) {157 this.appState.setParameter('isAuthorized', false);158 handled = true;159 }160 return handled;161 };162 return super.request(this.generateUrl(url), options).first().share()163 .map(response => response)164 .catch((error: any) => {165 return handleResponseError(error) ? Observable.of(error) : Observable.throw(error);166 });167 }168 get(url: string, params?: HomogeneousObject<string>, urlVariables?: HomogeneousObject<string>): Observable<Response> {169 const generatedUrl: string = this.generateUrlString(url, urlVariables);170 let response$: Observable<Response>;171 const options = this.generateOptions(url, params);172 if (this.shouldTurnGetToPost(generatedUrl)) {173 let body = (options && options.params) || params || {};174 if (body instanceof URLSearchParams) {175 const paramsMap = Array.from(body.paramsMap);176 body = paramsMap.reduce((current, param) => {177 const [key, value] = param;178 return {179 ...current,180 [key]: Array.isArray(value) && value.length === 1 ? value[0] : value181 };182 }, {});183 } else if (typeof body === 'string') {184 body = body.split('&').reduce((current, param): {[key: string]: any} => {185 const pair = param.split('=');186 return {187 ...current,188 [pair[0]]: decodeURIComponent(pair[1])189 };190 }, {});191 }192 options.params = {};193 response$ = super.post(generatedUrl, body, options);194 } else {195 response$ = super.get(this.generateUrlString(url, urlVariables), this.generateOptions(url, params));196 }197 return response$;198 }199 put(url: string, body: any, params?: HomogeneousObject<string>, urlVariables?: HomogeneousObject<string>): Observable<Response> {200 return super.put(this.generateUrlString(url, urlVariables), body, this.generateOptions(url, params));201 }202 post(url: string, body: any, params?: HomogeneousObject<string>, urlVariables?: HomogeneousObject<string>): Observable<Response> {203 return super.post(this.generateUrlString(url, urlVariables), body, this.generateOptions(url, params));204 }205 postFormData(206 url: string,207 params: HomogeneousObject<string>,208 options?: RequestOptionsArgs,209 urlVariables?: HomogeneousObject<string>): Observable<Response> {210 const encodedParams = this.generateOptions(url, params).params;211 let body;212 if (encodedParams && encodedParams instanceof URLSearchParams) {213 body = encodedParams.rawParams;214 }215 const requestOptions = Object.assign({}, options);216 if (!requestOptions.headers) {217 requestOptions.headers = new Headers();218 }219 requestOptions.headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');220 return super.post(this.generateUrlString(url, urlVariables), body, requestOptions);221 }...

Full Screen

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