Esempio n. 1
2
 streamPost(url: string, body: any): Observable<any> {
   const resultSubject = new Subject<any>();
   const request = new HttpRequest('POST', url, body, {
     responseType: 'text',
     reportProgress: true,
   });
   let lastSeq = -1;
   this.http.request(request).subscribe(
     (event: HttpEvent<any>) => {
       if (event.type != HttpEventType.DownloadProgress) return;
       let text = (event as HttpDownloadProgressEvent).partialText || '';
       if (text.startsWith('[')) {
         text = text.slice(1);
       }
       if (text.endsWith(']')) {
         text = text.slice(0, -1);
       }
       if (text.endsWith(',')) {
         text = text.slice(0, -1);
       }
       const msgs = JSON.parse('[' + text + ']');
       for (const msg of msgs) {
         if (lastSeq < msg['seq']) {
           resultSubject.next(msg);
           if (msg['done']) resultSubject.complete();
           lastSeq = msg['seq'];
         }
       }
     },
     error => {
       resultSubject.error(error);
     }
   );
   return resultSubject;
 }
    /**
     * Send the a http request the the given path.
     * Optionally accepts a request body.
     *
     * @param path the target path, usually starting with /rest
     * @param method the required HTTP method (i.e get, post, put)
     * @param data optional, if sending a data body is required
     * @param queryParams optional queryparams to append to the path
     * @param customHeader optional custom HTTP header of required
     * @param responseType optional response type, default set to json (i.e 'arraybuffer')
     * @returns a promise containing a generic
     */
    private async send<T>(
        path: string,
        method: HTTPMethod,
        data?: any,
        queryParams?: QueryParams,
        customHeader?: HttpHeaders,
        responseType?: string
    ): Promise<T> {
        // end early, if we are in history mode
        if (this.OSStatus.isInHistoryMode && method !== HTTPMethod.GET) {
            throw this.handleError('You cannot make changes while in history mode');
        }

        // there is a current bug with the responseType.
        // https://github.com/angular/angular/issues/18586
        // castting it to 'json' allows the usage of the current array
        if (!responseType) {
            responseType = 'json';
        }

        const url = path + formatQueryParams(queryParams);
        const options = {
            body: data,
            headers: customHeader ? customHeader : this.defaultHeaders,
            responseType: responseType as 'json'
        };

        try {
            return await this.http.request<T>(method, url, options).toPromise();
        } catch (e) {
            throw this.handleError(e);
        }
    }
    transmit(request: KalturaMultiRequest,  clientOptions: KalturaClientOptions, defaultRequestOptions: KalturaRequestOptions): Observable<KalturaMultiResponse> {

        const parameters = prepareParameters(request, clientOptions, defaultRequestOptions);

        const endpointUrl = createEndpoint(request, clientOptions, parameters['service'], parameters['action']);
        delete parameters['service'];
        delete parameters['action'];



        return this._http.request('post', endpointUrl,
            {
                body: parameters,
                headers: getHeaders()
            }).pipe(
            catchError(
                error => {
                    const errorMessage = error instanceof Error ? error.message : typeof error === 'string' ? error : null;
                    throw new KalturaClientException("client::multi-request-network-error", errorMessage || 'Error connecting to server');
                }
            ),
            map(
                result => {
                    try {
                        return request.handleResponse(result);
                    } catch (error) {
                        if (error instanceof KalturaClientException || error instanceof KalturaAPIException) {
                            throw error;
                        } else {
                            const errorMessage = error instanceof Error ? error.message : typeof error === 'string' ? error : null;
                            throw new KalturaClientException('client::multi-response-unknown-error', errorMessage || 'Failed to parse response');
                        }
                    }
                }));
    }
Esempio n. 4
0
    uploadFile(dataSetId: string, file: File): Observable<HttpEvent<DataSetFile>> {
        const formData = new FormData();
        formData.append("file", file, file.name);

        const request = new HttpRequest("POST", FileManagerService.getUploadsUrl(dataSetId), formData, {reportProgress: true});
        return this.http.request<DataSetFile>(request);
    }
  upload(file: File) {
    if (!file) { return; }

    // COULD HAVE WRITTEN:
    // return this.http.post('/upload/file', file, {
    //   reportProgress: true,
    //   observe: 'events'
    // }).pipe(

    // Create the request object that POSTs the file to an upload endpoint.
    // The `reportProgress` option tells HttpClient to listen and return
    // XHR progress events.
    const req = new HttpRequest('POST', '/upload/file', file, {
      reportProgress: true
    });

    // The `HttpClient.request` API produces a raw event stream
    // which includes start (sent), progress, and response events.
    return this.http.request(req).pipe(
      map(event => this.getEventMessage(event, file)),
      tap(message => this.showProgress(message)),
      last(), // return last (completed) message to caller
      catchError(this.handleError(file))
    );
  }
Esempio n. 6
0
    public send<TContent>(request: ApiRequest): Observable<ApiResponse<TContent>> {

        let options = this.buildOptions(request);

        let url = '/';
        if (this.baseAddress.endsWith('/') || request.requestUri.startsWith('/')) {
            url = '';
        }

        url = this.baseAddress + url + request.requestUri;

        return this.http.request<HttpResponse<TContent>>(request.method, url, options)
            .pipe(              
                map((response: HttpResponse<TContent>) => {
                    let apiResponse = new ApiResponse<TContent>(response);
                    return apiResponse;
                }),
                
                catchError((err, caught) => {

                    if (err.status === 401) {
                        return this.handleUnAuthorizedError<TContent>(err, url, request);
                    } else if(err.status === 403) {
                        return this.handleForbiddenError<TContent>();
                    }

                    return new Observable<ApiResponse<TContent>>();
                })

                
            );
    }
	// ---
	// PUBLIC METHODS.
	// ---

	// I make an HTTP request to the API and return an observable response.
	public makeRequest<T>( requestConfig: RequestConfig ) : Observable<T> {

		// The point of having a specialized API HttpClient is that you can bake-in logic
		// that is specific to this API, but not necessarily needed for any other
		// HttpClient in the application. There is a LOT you can do with this pattern;
		// but, for the PURPOSES OF THIS DEMO, we're only going to be sending the current
		// browser's timezone offset (in minutes).
		var headers: StringMap = {
			...requestConfig.headers,

			// Pass the timezone offset as a special HTTP header. This way, the server
			// can record this value if it has been changed (based on the user's locale).
			"X-Timezone-Offset": this.getTimezoneOffset()
		};

		var httpStream = this.httpClient.request<T>(
			requestConfig.method,
			requestConfig.url,
			{
				responseType: "json",
				headers: headers
			}
		);

		return( httpStream );

	}
Esempio n. 8
0
 public delete(url, params) : Observable<any> {
   return this.http.request('DELETE', url, {
     body: params
   })
   .map(this.success)
   .catch(this.error);
 }
Esempio n. 9
0
  uploadCities(data: string): Observable<HttpEvent<any>> {
    const req = new HttpRequest('POST', '/api/cities/uploads', data, {
      reportProgress: true,
    });

    return this.http.request(req);
  }
Esempio n. 10
0
 upload(path: string, file: File): Observable<any> {
   const req: HttpRequest<{}> = new HttpRequest('POST', path, file, {
     headers: this.headers,
     reportProgress: true,
     withCredentials: this.withCredentials,
   })
   return this.http.request(req)
 }