|
| 1 | +import { API_STATUS_CODES, APIOptions, FALLBACK_REQUEST_TIMEOUT, Host, ResponseType, ServerErrors } from '..' |
| 2 | +import { CoreAPIConstructorParamsType, FetchAPIParamsType, FetchInTimeParamsType } from './types' |
| 3 | +import { handleServerError } from './utils' |
| 4 | + |
| 5 | +class CoreAPI { |
| 6 | + handleLogout: () => void |
| 7 | + |
| 8 | + host: string |
| 9 | + |
| 10 | + timeout: number |
| 11 | + |
| 12 | + constructor({ handleLogout, host, timeout }: CoreAPIConstructorParamsType) { |
| 13 | + this.handleLogout = handleLogout |
| 14 | + this.host = host || Host |
| 15 | + this.timeout = timeout || FALLBACK_REQUEST_TIMEOUT |
| 16 | + } |
| 17 | + |
| 18 | + private fetchAPI = async <K = object>({ |
| 19 | + url, |
| 20 | + type, |
| 21 | + data, |
| 22 | + signal, |
| 23 | + preventAutoLogout = false, |
| 24 | + isMultipartRequest, |
| 25 | + }: FetchAPIParamsType<K>): Promise<ResponseType> => { |
| 26 | + const options: RequestInit = { |
| 27 | + method: type, |
| 28 | + signal, |
| 29 | + body: data ? JSON.stringify(data) : undefined, |
| 30 | + } |
| 31 | + // eslint-disable-next-line dot-notation |
| 32 | + options['credentials'] = 'include' as RequestCredentials |
| 33 | + return fetch( |
| 34 | + `${this.host}/${url}`, |
| 35 | + !isMultipartRequest |
| 36 | + ? options |
| 37 | + : ({ |
| 38 | + method: type, |
| 39 | + body: data, |
| 40 | + } as RequestInit), |
| 41 | + ).then( |
| 42 | + // eslint-disable-next-line consistent-return |
| 43 | + async (response) => { |
| 44 | + const contentType = response.headers.get('Content-Type') |
| 45 | + if (response.status === API_STATUS_CODES.UNAUTHORIZED) { |
| 46 | + if (preventAutoLogout) { |
| 47 | + throw new ServerErrors({ |
| 48 | + code: API_STATUS_CODES.UNAUTHORIZED, |
| 49 | + errors: [ |
| 50 | + { |
| 51 | + code: API_STATUS_CODES.UNAUTHORIZED, |
| 52 | + internalMessage: 'Please login again', |
| 53 | + userMessage: 'Please login again', |
| 54 | + }, |
| 55 | + ], |
| 56 | + }) |
| 57 | + } else { |
| 58 | + this.handleLogout() |
| 59 | + // Using this way to ensure that the user is redirected to the login page |
| 60 | + // and the component has enough time to get unmounted otherwise the component re-renders |
| 61 | + // and try to access some property of a variable and log exception to sentry |
| 62 | + // FIXME: Fix this later after analyzing impact |
| 63 | + // eslint-disable-next-line no-return-await |
| 64 | + return await new Promise((resolve) => { |
| 65 | + setTimeout(() => { |
| 66 | + resolve({ code: API_STATUS_CODES.UNAUTHORIZED, status: 'Unauthorized', result: [] }) |
| 67 | + }, 1000) |
| 68 | + }) |
| 69 | + } |
| 70 | + } else if (response.status >= 300 && response.status <= 599) { |
| 71 | + // FIXME: Fix this later after analyzing impact |
| 72 | + // eslint-disable-next-line no-return-await |
| 73 | + return await handleServerError(contentType, response) |
| 74 | + } else { |
| 75 | + if (contentType === 'application/json') { |
| 76 | + return response.json().then((responseBody) => { |
| 77 | + if (responseBody.code >= 300 && responseBody.code <= 599) { |
| 78 | + // Test Code in Response Body, despite successful HTTP Response Code |
| 79 | + throw new ServerErrors({ code: responseBody.code, errors: responseBody.errors }) |
| 80 | + } else { |
| 81 | + // Successful Response. Expected Response Type {code, result, status} |
| 82 | + return responseBody |
| 83 | + } |
| 84 | + }) |
| 85 | + } |
| 86 | + if (contentType === 'octet-stream' || contentType === 'application/octet-stream') { |
| 87 | + // used in getArtifact() API only |
| 88 | + return response |
| 89 | + } |
| 90 | + } |
| 91 | + }, |
| 92 | + (error) => { |
| 93 | + // Network call fails. Handle Failed to Fetch |
| 94 | + const err = { |
| 95 | + code: 0, |
| 96 | + userMessage: error.message, |
| 97 | + internalMessage: error.message, |
| 98 | + moreInfo: error.message, |
| 99 | + } |
| 100 | + throw new ServerErrors({ code: 0, errors: [err] }) |
| 101 | + }, |
| 102 | + ) |
| 103 | + } |
| 104 | + |
| 105 | + private fetchInTime = <T = object>({ |
| 106 | + url, |
| 107 | + type, |
| 108 | + data, |
| 109 | + options, |
| 110 | + isMultipartRequest, |
| 111 | + }: FetchInTimeParamsType<T>): Promise<ResponseType> => { |
| 112 | + const controller = options?.abortControllerRef?.current ?? new AbortController() |
| 113 | + const signal = options?.abortControllerRef?.current?.signal || options?.signal || controller.signal |
| 114 | + const timeoutPromise: Promise<ResponseType> = new Promise((resolve, reject) => { |
| 115 | + const timeout = options?.timeout || this.timeout |
| 116 | + |
| 117 | + setTimeout(() => { |
| 118 | + controller.abort() |
| 119 | + if (options?.abortControllerRef?.current) { |
| 120 | + // eslint-disable-next-line no-param-reassign |
| 121 | + options.abortControllerRef.current = new AbortController() |
| 122 | + } |
| 123 | + |
| 124 | + // Note: This is not catered in case abortControllerRef is passed since |
| 125 | + // the API is rejected with abort signal from line 202 |
| 126 | + // FIXME: Remove once signal is removed |
| 127 | + // eslint-disable-next-line prefer-promise-reject-errors |
| 128 | + reject({ |
| 129 | + code: API_STATUS_CODES.REQUEST_TIMEOUT, |
| 130 | + errors: [ |
| 131 | + { |
| 132 | + code: API_STATUS_CODES.REQUEST_TIMEOUT, |
| 133 | + internalMessage: 'Request cancelled', |
| 134 | + userMessage: 'Request Cancelled', |
| 135 | + }, |
| 136 | + ], |
| 137 | + }) |
| 138 | + }, timeout) |
| 139 | + }) |
| 140 | + return Promise.race([ |
| 141 | + this.fetchAPI({ |
| 142 | + url, |
| 143 | + type, |
| 144 | + data, |
| 145 | + signal, |
| 146 | + preventAutoLogout: options?.preventAutoLogout || false, |
| 147 | + isMultipartRequest, |
| 148 | + }), |
| 149 | + timeoutPromise, |
| 150 | + ]).catch((err) => { |
| 151 | + if (err instanceof ServerErrors) { |
| 152 | + throw err |
| 153 | + } else { |
| 154 | + // FIXME: Can be removed once signal is removed |
| 155 | + throw new ServerErrors({ |
| 156 | + code: API_STATUS_CODES.REQUEST_TIMEOUT, |
| 157 | + errors: [ |
| 158 | + { |
| 159 | + code: API_STATUS_CODES.REQUEST_TIMEOUT, |
| 160 | + internalMessage: 'That took longer than expected.', |
| 161 | + userMessage: 'That took longer than expected.', |
| 162 | + }, |
| 163 | + ], |
| 164 | + }) |
| 165 | + } |
| 166 | + }) |
| 167 | + } |
| 168 | + |
| 169 | + post = <T = any, K = object>( |
| 170 | + url: string, |
| 171 | + data: K, |
| 172 | + options?: APIOptions, |
| 173 | + isMultipartRequest?: boolean, |
| 174 | + ): Promise<ResponseType<T>> => this.fetchInTime<K>({ url, type: 'POST', data, options, isMultipartRequest }) |
| 175 | + |
| 176 | + put = <T = any, K = object>(url: string, data: K, options?: APIOptions): Promise<ResponseType<T>> => |
| 177 | + this.fetchInTime<K>({ url, type: 'PUT', data, options }) |
| 178 | + |
| 179 | + patch = <T = any, K = object>(url: string, data: K, options?: APIOptions): Promise<ResponseType<T>> => |
| 180 | + this.fetchInTime<K>({ url, type: 'PATCH', data, options }) |
| 181 | + |
| 182 | + get = <T = any>(url: string, options?: APIOptions): Promise<ResponseType<T>> => |
| 183 | + this.fetchInTime({ url, type: 'GET', data: null, options }) |
| 184 | + |
| 185 | + trash = <T = any, K = object>(url: string, data?: K, options?: APIOptions): Promise<ResponseType<T>> => |
| 186 | + this.fetchInTime<K>({ url, type: 'DELETE', data, options }) |
| 187 | +} |
| 188 | + |
| 189 | +export default CoreAPI |
0 commit comments