Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.44 KB | None | 0 0
  1. import {assertNotNull} from "../../common/assertNotNull";
  2. import {UrlHelper} from "../../common/helpers";
  3. import {localization} from "../../common/localization/localization";
  4. import {ExceptionType} from "../exceptionTypes";
  5. import {appSettingsProvider} from "../settings";
  6.  
  7. export interface IRequestOptions {
  8. getToken: () => string | null;
  9. setToken: (token: string | null) => void;
  10. onAuthError: () => void;
  11. getEmail: () => string | null;
  12. setEmail: (email: string) => void;
  13. }
  14.  
  15. export class BaseRequest {
  16. static handleError = (error: any): Promise<any> => {
  17. return Promise.reject(error);
  18. };
  19.  
  20. static globalOptions: IRequestOptions;
  21.  
  22. private readonly emptyResponse: EmptyResponse;
  23.  
  24. protected get options(): IRequestOptions {
  25. return (
  26. BaseRequest.globalOptions || {
  27. getToken: (): string | null => null,
  28. getEmail: (): string | null => null,
  29. onAuthError: (): void => console.warn("onAuthError is not set")
  30. }
  31. );
  32. }
  33.  
  34. protected static accessToken: string = "";
  35.  
  36. constructor() {
  37. this.emptyResponse = new EmptyResponse();
  38. }
  39.  
  40. public static setAccessToken(token: string): void {
  41. this.accessToken = token;
  42. }
  43.  
  44. protected attachHeaders(headers: any): any {
  45. const result: any = {
  46. ...headers,
  47. // "Content-Type": "application/x-www-form-urlencoded",
  48. "Accept": "application/json"
  49. };
  50.  
  51. if (BaseRequest.accessToken && !headers.Authorization) {
  52. result.Authorization = `Bearer ${BaseRequest.accessToken}`;
  53. }
  54.  
  55. return result;
  56. }
  57.  
  58. protected async fetch(url: string, config: any = {}, isFullUrl?: boolean): Promise<any> {
  59. let isRequestError = false;
  60. let status: number | null = null;
  61. //const customHeaders = config.headers != undefined ? config.headers : {};
  62.  
  63. try {
  64. //const headers = this.attachHeaders(customHeaders);
  65. const token = await BaseRequest.globalOptions.getToken()
  66. const username = await BaseRequest.globalOptions.getEmail()
  67. const method: boolean = config.method === "GET" ? true : false
  68. const query: any = method ? `?token=${token}&username=${username}` : '';
  69.  
  70. // config = Object.assign(config, {
  71. // headers: headers,
  72. // });
  73.  
  74. if ( config.body ) {
  75. if(token){
  76. config.body = {...config.body, username, token} //add token in body
  77. }
  78. config.body = this.fd(config.body || {})
  79. } else if ( config.json ) {
  80. if(token){
  81. config.json = {...config.json, username, token}
  82. }
  83. config.body = JSON.stringify(config.json)
  84. }
  85.  
  86. url = isFullUrl ? url : this.createUrl(url);
  87.  
  88. const response: any = await Promise.race(
  89. [
  90. fetch(
  91. `${url}${query}`,
  92. (!method && config)
  93. ),
  94. new Promise((resolve: any, reject: any): void => {
  95. setTimeout(
  96. () => reject(new Error("Network request failed")),
  97. appSettingsProvider.settings.fetchTimeout
  98. );
  99. })
  100. ]
  101. );
  102.  
  103. status = (response || {}).status;
  104. if (response.status == 204) {
  105. return this.emptyResponse;
  106. } else if (response.status == 404) {
  107. isRequestError = true;
  108. throw new Error(localization.errors.notFound);
  109. } else if (!response.status || response.status < 200 || response.status >= 300) {
  110. isRequestError = true;
  111. throw await response.json();
  112. }
  113. const json: object = await response.json();
  114. console.log(json);
  115.  
  116.  
  117. return json;
  118. } catch (error) {
  119. if (!isRequestError) {
  120. console.warn(localization.errors.noInternetConnection, error);
  121. const connectionError: any = new Error(error.message);
  122. connectionError.name = ExceptionType.Connection;
  123. connectionError.innerError = error;
  124. connectionError.url = url;
  125. if (error.message == "Network request failed") {
  126. connectionError.message = localization.errors.noInternetConnection;
  127. }
  128.  
  129. throw connectionError;
  130. } else {
  131. error.isServerError = true;
  132. console.warn(error, "Request error", {url, status});
  133. if (error.message == null
  134. || error.message.startsWith("JSON")
  135. || error.message.startsWith("Unexpected")) {
  136. error.message = localization.errors.unknownError;
  137. }
  138. throw error;
  139. }
  140. }
  141. }
  142.  
  143. protected createUrl(relativeUrl: string): string {
  144. return UrlHelper.create(relativeUrl, this.getUrl());
  145. }
  146.  
  147. protected fd(params: { [key: string]: any }): FormData {
  148. const result: FormData = new FormData();
  149. for ( const i in params ) {
  150. if ( params.hasOwnProperty(i) ) {
  151. result.append(i, params[i]);
  152. }
  153. }
  154.  
  155. return result;
  156. }
  157. //params: { [key: string]: string | number | boolean | string | Date | null
  158. protected q(params: { [key: string]: string, }): string {
  159. const query = Object.keys(params)
  160. .filter((k) => params[k] != null)
  161. .map((k) => `${k}=${encodeURIComponent(assertNotNull(
  162. typeof params[k] === "object" ? JSON.stringify(params[k]) : params[k]
  163. ).toString())}`)
  164. .join("&");
  165.  
  166. return query ? `?${query}` : "";
  167. }
  168.  
  169. private getUrl(): string {
  170. return appSettingsProvider.settings.serverUrl;
  171. }
  172. }
  173.  
  174. class EmptyResponse {
  175. public json(): any {
  176. return null;
  177. }
  178. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement