Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {assertNotNull} from "../../common/assertNotNull";
- import {UrlHelper} from "../../common/helpers";
- import {localization} from "../../common/localization/localization";
- import {ExceptionType} from "../exceptionTypes";
- import {appSettingsProvider} from "../settings";
- export interface IRequestOptions {
- getToken: () => string | null;
- setToken: (token: string | null) => void;
- onAuthError: () => void;
- getEmail: () => string | null;
- setEmail: (email: string) => void;
- }
- export class BaseRequest {
- static handleError = (error: any): Promise<any> => {
- return Promise.reject(error);
- };
- static globalOptions: IRequestOptions;
- private readonly emptyResponse: EmptyResponse;
- protected get options(): IRequestOptions {
- return (
- BaseRequest.globalOptions || {
- getToken: (): string | null => null,
- getEmail: (): string | null => null,
- onAuthError: (): void => console.warn("onAuthError is not set")
- }
- );
- }
- protected static accessToken: string = "";
- constructor() {
- this.emptyResponse = new EmptyResponse();
- }
- public static setAccessToken(token: string): void {
- this.accessToken = token;
- }
- protected attachHeaders(headers: any): any {
- const result: any = {
- ...headers,
- // "Content-Type": "application/x-www-form-urlencoded",
- "Accept": "application/json"
- };
- if (BaseRequest.accessToken && !headers.Authorization) {
- result.Authorization = `Bearer ${BaseRequest.accessToken}`;
- }
- return result;
- }
- protected async fetch(url: string, config: any = {}, isFullUrl?: boolean): Promise<any> {
- let isRequestError = false;
- let status: number | null = null;
- //const customHeaders = config.headers != undefined ? config.headers : {};
- try {
- //const headers = this.attachHeaders(customHeaders);
- const token = await BaseRequest.globalOptions.getToken()
- const username = await BaseRequest.globalOptions.getEmail()
- const method: boolean = config.method === "GET" ? true : false
- const query: any = method ? `?token=${token}&username=${username}` : '';
- // config = Object.assign(config, {
- // headers: headers,
- // });
- if ( config.body ) {
- if(token){
- config.body = {...config.body, username, token} //add token in body
- }
- config.body = this.fd(config.body || {})
- } else if ( config.json ) {
- if(token){
- config.json = {...config.json, username, token}
- }
- config.body = JSON.stringify(config.json)
- }
- url = isFullUrl ? url : this.createUrl(url);
- const response: any = await Promise.race(
- [
- fetch(
- `${url}${query}`,
- (!method && config)
- ),
- new Promise((resolve: any, reject: any): void => {
- setTimeout(
- () => reject(new Error("Network request failed")),
- appSettingsProvider.settings.fetchTimeout
- );
- })
- ]
- );
- status = (response || {}).status;
- if (response.status == 204) {
- return this.emptyResponse;
- } else if (response.status == 404) {
- isRequestError = true;
- throw new Error(localization.errors.notFound);
- } else if (!response.status || response.status < 200 || response.status >= 300) {
- isRequestError = true;
- throw await response.json();
- }
- const json: object = await response.json();
- console.log(json);
- return json;
- } catch (error) {
- if (!isRequestError) {
- console.warn(localization.errors.noInternetConnection, error);
- const connectionError: any = new Error(error.message);
- connectionError.name = ExceptionType.Connection;
- connectionError.innerError = error;
- connectionError.url = url;
- if (error.message == "Network request failed") {
- connectionError.message = localization.errors.noInternetConnection;
- }
- throw connectionError;
- } else {
- error.isServerError = true;
- console.warn(error, "Request error", {url, status});
- if (error.message == null
- || error.message.startsWith("JSON")
- || error.message.startsWith("Unexpected")) {
- error.message = localization.errors.unknownError;
- }
- throw error;
- }
- }
- }
- protected createUrl(relativeUrl: string): string {
- return UrlHelper.create(relativeUrl, this.getUrl());
- }
- protected fd(params: { [key: string]: any }): FormData {
- const result: FormData = new FormData();
- for ( const i in params ) {
- if ( params.hasOwnProperty(i) ) {
- result.append(i, params[i]);
- }
- }
- return result;
- }
- //params: { [key: string]: string | number | boolean | string | Date | null
- protected q(params: { [key: string]: string, }): string {
- const query = Object.keys(params)
- .filter((k) => params[k] != null)
- .map((k) => `${k}=${encodeURIComponent(assertNotNull(
- typeof params[k] === "object" ? JSON.stringify(params[k]) : params[k]
- ).toString())}`)
- .join("&");
- return query ? `?${query}` : "";
- }
- private getUrl(): string {
- return appSettingsProvider.settings.serverUrl;
- }
- }
- class EmptyResponse {
- public json(): any {
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement