-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrc_api_serverInterceptor.ts
More file actions
63 lines (46 loc) · 2.09 KB
/
src_api_serverInterceptor.ts
File metadata and controls
63 lines (46 loc) · 2.09 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
import { Store, AnyAction } from 'redux'
import { AxiosResponse } from 'axios'
import get from 'lodash/get'
import localStorage from 'redux-persist/es/storage'
import * as coreActions from 'src/modules/core/core.actions'
import { LOCAL_STORAGE_KEYS, PATHS } from 'src/constants'
import history from 'src/utils/history'
import { qnotification } from 'quantum_components'
import NOTIFICATION_TYPES from 'src/constants/notificationTypes'
type Interceptor = (error: any) => any
const serverSuccessInterceptor = (): Interceptor => async (response: AxiosResponse): Promise<AxiosResponse | void> => {
if (response.data.data && response.data.data.message) {
qnotification({
type: NOTIFICATION_TYPES.SUCCESS,
message: response.data.data.message,
})
}
return Promise.resolve(response)
}
const serverErrorInterceptor = (store: Store<any, AnyAction>): Interceptor => async (
error: AxiosResponse
): Promise<AxiosResponse | void> => {
if (error.status >= 500) {
qnotification({ type: NOTIFICATION_TYPES.ERROR, message: error.status, description: 'Something went wrong.' })
return Promise.reject(error)
}
qnotification({ type: NOTIFICATION_TYPES.ERROR, message: error.data.error.message })
if (get(error, 'config.skipError', false)) return Promise.reject(error)
const statusesNoErrors = get(error, 'config.statusesNoErrors', [])
if (statusesNoErrors.includes(error.status)) return Promise.reject(error)
if (error.status === 401 || error.status === 403) {
localStorage.removeItem(LOCAL_STORAGE_KEYS.ACCESS_TOKEN)
store.dispatch(coreActions.logoutSuccess())
history.push(PATHS.SIGN_IN)
return Promise.reject(error)
}
const isServerError = error.status > 300
if (!isServerError) return Promise.reject(error)
const isHtmlResponseError = get(error, 'headers.content-type', '').includes('text/html')
const errorType = isHtmlResponseError ? 'html' : 'text'
store.dispatch(
coreActions.setServerError(get(error, 'data.message') || JSON.stringify(error.data) || String(error), errorType)
)
return error
}
export { serverSuccessInterceptor, serverErrorInterceptor }