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